Displaying an explicit number of nested attributes in a Rails form
Given three models:
- Document
- Asset
- AssetCategory
A document accepts_nested_attributes_for assets (a document has_many assets), and an asset belongs_to an asset category.
I would like to display a field for an asset attribute for each asset category.
I am currently achieving this as follows. Controller:
def new
@document = Document.new
@asset_categories = AssetCategory.all
@asset_categories.count.times { @document.assets.build }
end
View (this example uses the semantic_fields_for method provided by Formtastic, but this is just a thin wrapper around fields_for):
i=0
f.semantic_fields_开发者_开发技巧for :assets do |asset_form|
asset_form.input :attachment, :label => @asset_categories[i].name
asset_form.input :asset_category, :as => :hidden, :value => @asset_categories[i].id
i+=1
end
Is there a cleaner approach to this? I'm not so fond of the temporary variable i.
In the controller:
def new
@document = Document.new
AssetCategory.all.each do |ac|
@document.assets.build :asset_category_id=>ac.id
end
end
In the view:
f.semantic_fields_for :assets do |af|
af.input :attachment, :label=>af.object.asset_category.name
af.input :asset_category_id, :as => :hidden, :value => af.object.asset_category.id
end
精彩评论