-
-
Save yortz/1128473 to your computer and use it in GitHub Desktop.
Using nested_for_for with rails_admin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Product < ActiveRecord::Base | |
has_many :material_product_mappings, :dependent => :destroy, :inverse_of => :product | |
has_many :materials, :through => :material_product_mappings, :autosave => true | |
#... | |
rails_admin do | |
list do | |
field :material_product_mappings do | |
label "Materials" | |
visible true | |
end | |
#... | |
end | |
edit do | |
form_builder :nested_form_for | |
field :material_product_mappings do | |
label "Materials" | |
partial "edit_material_product_mappings" | |
end | |
#... | |
end | |
end | |
end | |
class MaterialProductMapping < ActiveRecord::Base | |
belongs_to :product, :inverse_of => :material_product_mappings | |
belongs_to :material, :inverse_of => :material_product_mappings | |
validates :num_units, | |
:numericality => { :greater_than_or_equal_to => 0 } | |
def name | |
"#{self.material.name} (#{self.material.unit.name}) x #{self.num_units}" | |
end | |
rails_admin do | |
label "Materials" | |
visible false | |
end | |
end | |
# file .../app/views/rails_admin/main/_edit_material_product_mappings.html.erb | |
<div class="field <%= field.dom_id %>"> | |
<% _saved_object = @object %> | |
<% _saved_form = form %> | |
<% _saved_field = field %> | |
<%= label_tag(field.dom_id, field.label) %> | |
<div style="clear:left;padding-left:100px"> | |
<%= form.fields_for(:material_product_mappings) %> | |
<p> | |
<%= form.link_to_add('Add Material ', :material_product_mappings) %> | |
</p> | |
<% @object = _saved_object %> | |
<% form = _saved_form %> | |
<% field = _saved_field %> | |
<% if field.has_errors? %> | |
<span class="errorMessage"><%= "#{field.label } #{field.errors.first}" %></span> | |
<% end %> | |
</div> | |
</div> | |
# file .../app/views/rails_admin/main/_material_product_mapping_fields.html.erb | |
# nested form looks for this file... | |
<% ff = f %> | |
<% ff.object.errors.full_messages.each do |msg| %> | |
<p class="flash_alert_msg"><%= msg %></p> | |
<% end %> | |
<%= ff.number_field(:num_units, :min => 0.0, :step => 0.01, :size => 6, :style => "text-align:right") %> | |
<%= ff.collection_select('material_id',Material.active,:id,:name,:prompt => false) %> | |
<%= ff.link_to_remove('Remove') %> | |
# also need to copy app/views/layouts/rails_admin/_head.html.haml from the rails_admin installation to | |
# your app and modify it to include nested_form's JS. add the following line: | |
- head_javascript "nested_form" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment