在视图中未显示fields_for has_many关联的复数 [英] Plural for fields_for has_many association not showing in view
问题描述
当前,项目 属于 公司和 has_many ItemVariants .
我正在尝试使用嵌套的fields_for通过Item表单添加ItemVariant字段,但是使用:item_variants不会显示该表单.仅在使用单数时显示.
I'm trying to use nested fields_for to add ItemVariant fields through the Item form, however using :item_variants does not display the form. It is only displayed when I use the singular.
我检查了我的关联,它们似乎是正确的,这可能与嵌套在Company下的项目有关,还是我想念其他东西?
I have check my associations and they seem to be correct, could it possibly have something to do with item being nested under Company, or am I missing something else?
谢谢.
注意:以下代码段中已省略了无关的代码.
编辑:不知道这是否相关,但是我正在使用CanCan进行身份验证.
Don't know if this is relevant, but I'm using CanCan for Authentication.
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 %>
推荐答案
您应该用一些数据预填充@item.item_variants
:
You should prepopulate @item.item_variants
with some data:
def new # in the ItemController
...
@item = Item.new
3.times { @item.item_variants.build }
...
end
来源: http://rubysource.com/complex-rails-forms-with-nested-属性/
这篇关于在视图中未显示fields_for has_many关联的复数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!