【问题标题】:Rails Migration Form Error With Id带有 ID 的 Rails 迁移表单错误
【发布时间】:2013-05-01 21:11:14
【问题描述】:

我刚刚为我的电影表构建了一个名为 year_id 的迁移 当我创建两个新年份,2012 年和 2013 年时,然后添加下拉列表以选择年份 我明白了:

如何让我的下拉选择显示实际年份(2012 年或 2013 年)而不是 #

这是我的模型:

class Year < ActiveRecord::Base
    attr_accessible :year 
    has_many :movies
end 

这是我的表格:

<%= semantic_form_for @movie, :html => { :multipart => true } do |f| %> 
  <% if @movie.errors.any? %> 
    <div id="error_explanation"> 
      <h2>
        <%= pluralize(@movie.errors.count, "error") %> prohibited this movie from being saved:
      </h2> 
      <ul> 
        <% @movie.errors.full_messages.each do |msg| %> 
          <li><%= msg %></li> 
        <% end %> 
      </ul>
    </div> 
  <% end %> 
  <div class="field"> <%=h f.input :year, :include_blank => false %> </div><br />

【问题讨论】:

  • 你能把你的 Year 模型的内容贴出来吗?谢谢
  • 类年
  • 请分享选择的代码,基本上你得到的是对象而不是year属性。
  • 这是形式 { :multipart => true } do |f| %>

    禁止保存这部电影:

    false %>

  • @ 符号通常没有间隔,但 stackoverflow 不允许,因此为此进行了更改

标签: ruby-on-rails forms migration semantics


【解决方案1】:

如果没有看到表单的完整代码,很难准确回答您的问题。但是,正在发生的事情是您的 Year 的实际实例正在作为选项文本传递。如果您从控制台调用 to_s,您可能会看到类似的输出

Year.first.to_s
# => "#<Year:0x00000101bcea10>"

查看http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select 上的options_for_select 文档,了解如何正确定义选择元素的选项。

看起来您也可以使用collection_select 表单助手来省去定义选项数组的麻烦。它看起来像这样

<%= f.collection_select :year_id, Year.all, :id, :year %>

最后一个选项:year 是用于选项文本的方法,因此您可以将其更改为对您的模型有意义的内容。

【讨论】:

  • 是的,他是对的,您需要使用 collection_select、options_for_select 或 options_from_collection_for_select 才能正确显示内容。
猜你喜欢
  • 1970-01-01
  • 2011-07-28
  • 2015-04-04
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 2014-10-30
相关资源
最近更新 更多