Skip to content

Instantly share code, notes, and snippets.

@matatabi
Created January 28, 2011 17:23
Show Gist options
  • Save matatabi/800590 to your computer and use it in GitHub Desktop.
Save matatabi/800590 to your computer and use it in GitHub Desktop.
nested_attributes の使用例 (フォーム内で子オブジェクトを参照する方法含む)
def link_to_remove_fields(name, f)
# See corresponding remove_fields function in application.js
f.hidden_field(:_destroy) + link_to(name, nil, :onclick => "remove_fields(this)", :remote=>true)
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
html = link_to(raw("<img src='/images/icons/plus.gif' />"), nil, :onclick => h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"), :remote => true)
html << link_to(name, nil, :onclick => h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"), :remote => true)
return html
end
class DetailedImage < ActiveRecord::Base
belongs_to :product
end
<%= f.file_field :image, :type=>:file %>
<%= link_to_remove_fields image_tag('/images/icons/cross.gif'), f %>
<% if f.object.id %>
<%= f.object.name %>
<% end %>
f.options[:child_index] returns 1296474703879
But note the above only works for new forms added through link_to_add_fields
The best thing to do is to get the name of the object itself
f.object_name returns product[category_products_attributes][1296474703879]
Or if you really just want the index, gsub it
f.object_name.gsub(/[^0-9]+/,'')
<%= form_for([:vendor, @product], :html => {:multipart => true, :class => "std", :name=>'f' }) do |f| %>
<%= error_messages_for 'product', 'product_vendor' %>
<!-- ... product fields -->
<%= f.fields_for :detailed_images do |builder| %>
<%= render "detailed_image_fields", :f => builder %>
<% end %>
<%= link_to_add_fields t('action.add_obj', :obj => DetailedImage.model_name.human), f, :detailed_images %>
<% end %>
class Product < ActiveRecord::Base
has_many :detailed_images, :dependent => :destroy, :order => "sort_id ASC"
accepts_nested_attributes_for :detailed_images, :reject_if => lambda { |a| a[:name].blank?}, :allow_destroy => true
end
@product = Product.find(params[:id)
@product.detailed_images_attributes = [{:something => x}, {:something => y]
# Or, you can do
@product.detailed_images.build({:something => x})
@product.detailed_images.build({:something => y})
# Or
3.times do
@product.detailed_images.build
end
# Build is different if using a has_one relationship
@product.build_detailed_image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment