【问题标题】:Rails saving 0 instead of string from model collection_selectRails 从模型 collection_select 中保存 0 而不是字符串
【发布时间】:2012-04-22 00:20:20
【问题描述】:

我一直在尝试创建一个基本的 Rails 应用程序。我使用 generate 创建了一个基本的脚手架,并在球员和球队之间建立了 belongs_to 关系,所以球员 belongs_to 球队和球队 has_many 球员。

我的表单视图是这样的

<%= 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 显示编辑销毁

新团队

最初我有这样的集合选择 &lt;%= f.collection_select :Playertwo, Player.all, :id, :firstname %&gt; 这会插入 ID,但我希望插入文本。

我查看了大量的文档,并在我仍在学习的过程中找到了王牌。

感谢您的帮助:)

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    那么这取决于您的迁移。如果您在数据库中创建了整数字段,则保存字符串将保存 0。

    您可以 (a) 将迁移更改为使用字符串而不是整数。

    您可以 (b),使用 id,并通过查找名称来显示名称。

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

    你可以从所属队伍中获取名字_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

    【讨论】:

    • 我提到我最初有 :id 但这放置了玩家的 ID,而我想要玩家名字的字符串。这可能吗?
    • 太棒了!谢谢一群人!最初我有一个整数作为值,然后我将迁移更改为字符串并执行了 rake db:reset。很多文档让我对 Rails 世界的新手感到有些困惑。这是一个巨大的帮助。
    • 好的,我将团队的模型更改为 class Team &lt; ActiveRecord::Base belongs_to :playerone, :class_name =&gt; "Player" belongs_to :playertwo, :class_name =&gt; "Player" end,并将视图更改为使用 ``,但现在我得到了“团队中的 NoMethodError”# show Showing c:/Sites/TWL/app/views/teams/show.html.erb where line #5 raise: undefined method `firstname' for nil:NilClass' 有什么想法吗?
    • 在之前的回答(不同的问题)上,有人告诉我我不需要这些关系。我已经点击了文档,您的回答使我朝着正确的方向前进。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    相关资源
    最近更新 更多