簡體   English   中英

Rails從模型collection_select中保存0而不是字符串

[英]Rails saving 0 instead of string from model collection_select

我一直在嘗試創建一個基本的rails應用程序。 我使用generate來創建一個基本的腳手架,我在玩家和團隊之間設置了belongs_to關系,因此玩家屬於團隊和團隊擁有很多玩家。

我的表單視圖看起來像這樣

<%= form_for(@team) do |f| %>
  <% if @team.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@team.errors.count, "error") %> prohibited this team from being saved:</h2>

      <ul>
      <% @team.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :Playerone %><br />
    <%= f.collection_select :Playerone, Player.all, :firstname, :firstname %>
  </div>

  <div class="field">
    <%= f.label :Playertwo %><br />
    <%= f.collection_select :Playertwo, Player.all, :firstname, :firstname %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

當我嘗試創建一個新團隊時,我得到了下拉列表,因為我希望它們與玩家的名字一起選擇,但是當它被保存時,它將0保存為記錄。

上市團隊

Playerone Playertwo
0 0顯示編輯毀滅

新團隊

最初我有這樣的集合選擇如下<%= f.collection_select :Playertwo, Player.all, :id, :firstname %>這會插入ID,但我希望插入文本。

我已經查看了大量的文檔,並且在我還在學習的時候已經拿到了王牌。

謝謝你的幫助 :)

那么這取決於您的遷移。 如果在數據庫中創建了整數字段,則保存字符串將保存0。

您可以(a)將遷移更改為使用字符串而不是整數。

您可以(b)使用id,並通過查找名稱來顯示名稱。

f.collection_select :Playertwo, Player.all, :id, :firstname

您可以從團隊belongs_to playerone和playertwo獲取名稱,

class Team
  belongs_to :playerone, :class_name => "Player"
  belongs_to :playertwo, :class_name => "Player"
end

<%= team.playerone.firstname %>

或者您可以將名字委托給玩家。

class Team
  belongs_to :playerone, :class_name => "Player"
  belongs_to :playertwo, :class_name => "Player"
  delegate :firstname, :to => :playerone, :prefix => true, :allow_nil => true
  delegate :firstname, :to => :playertwo, :prefix => true, :allow_nil => true
end

<%= team.playerone_firstname %>

或者您可以(c)使用belongs_to,它使用整數。 請查閱文檔http://guides.rubyonrails.org/getting_started.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM