【问题标题】:Plural for fields_for has_many association not showing in viewfields_for has_many 关联的复数未显示在视图中
【发布时间】:2012-10-20 11:29:52
【问题描述】:

目前,Item belongs_to Companyhas_many ItemVariants

我正在尝试使用嵌套 fields_for 通过 Item 表单添加 ItemVariant 字段,但是使用 :item_variants 不会显示表单。只有当我使用单数时才会显示。

我检查了我的关联,它们似乎是正确的,这可能与嵌套在公司下的项目有关,还是我遗漏了其他东西?

提前致谢。

注意:下面的 sn-ps 中省略了不相关的代码。

编辑:不知道这是否相关,但我正在使用 CanCan 进行身份验证。

routes.rb

resources :companies do
  resources :items
end

item.rb

class Item < ActiveRecord::Base
  attr_accessible :name, :sku, :item_type, :comments, :item_variants_attributes


  # Associations
  #-----------------------------------------------------------------------
  belongs_to :company
  belongs_to :item_type
  has_many   :item_variants

  accepts_nested_attributes_for :item_variants, allow_destroy: true

end

item_variant.rb

class ItemVariant < ActiveRecord::Base
  attr_accessible :item_id, :location_id

  # Associations
  #-----------------------------------------------------------------------
  belongs_to :item

end

item/new.html.erb

<%= form_for [@company, @item] do |f| %>
  ...
  ...
  <%= f.fields_for :item_variants do |builder| %>
    <fieldset>
      <%= builder.label :location_id %>
      <%= builder.collection_select :location_id, @company.locations.order(:name), :id, :name, :include_blank => true %>
    </fieldset>
  <% end %>
  ...
  ...
<% end %>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 nested-attributes fields-for


    【解决方案1】:

    您应该使用一些数据预填充@item.item_variants

    def new # in the ItemController
      ...
      @item = Item.new
      3.times { @item.item_variants.build }
      ...
    end
    

    来源:http://rubysource.com/complex-rails-forms-with-nested-attributes/

    【讨论】:

    • 谢谢!工作得很好,但作为参考,我使用的是 RailsCast ep 196-Nested-model-form-revised。在他的新行动中,它只包含@survey = Survey.new,没有建立关联。知道为什么我需要建立关联而 Ryan 没有/没有吗?
    • railscast 更好,虽然复杂,因为它可以在调查表中动态添加问题。所以它不需要预先填充任何东西。
    • 我只是想为那些对 .build 以及为什么 Ryans 不需要它感到困惑的人补充一些含义。如果您在第 3 行的 appliation_helper 中查看他的代码,它会创建类实例。所以它取代了.build。希望这对其他人有帮助!
    【解决方案2】:

    试试这个方法

    在你的item controllernew action写下

    def new
      ...
        @item = # define item here
        @item.item_variants.build if @item.item_variants.nil?
      ...
    end
    

    item/new.html.erb

    <%= form_for @item do |f| %>
      ...
      ...
      <%= f.fields_for :item_variants do |builder| %>
        ...
      <% end %>
      ...
      ...
    <% end %>
    

    更多请看视频 - Nested Model Form

    【讨论】:

    • 谢谢。得到它的工作,但使用@item.item_variants.build if @item.item_variants.nil? 没有工作。它仅在我删除 if 语句时才有效。此外,使用您的链接的修订版本让我感到困惑。在他的控制器中,他不使用 .build。他只创建@survey 实例。知道为什么我需要建立协会而 Ryan 没有/没有吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2023-03-26
    相关资源
    最近更新 更多