Rails Nested Model - remove association

What is the equivalent of <%= f.hidden_field :_destroy %> for invalidation instead of annihilation? (I just had to remove it from the association, but I do not want to destroy it).

Example situation:

 class Foo < ActiveRecord::Base has_many :bar, :dependent=>:nullify, :autosave=>true accepts_nested_attributes_for :bar, :reject_if => proc { |attributes| attributes.all? {|k,v| v.blank?} } class Bar < ActiveRecord::Base belongs_to :foo 

In Foo edit.html.erb :

 <%= f.fields_for :bar do |builder| %> <%= builder.some_rails_helper %> <%= builder.hidden_field :_remove #<-- set value to 1 to destroy, but how to unassociate?%> <% end %> 

One small solution modification

 def remove #!self.foo_id.nil? should be: false #this way newly created objects aren't destroyed, and neither are existing ones. end 

So now I can call .edit.html:

 <%= builder.hidden_field :_remove %> 
+4
source share
1 answer

Create a method like this:

 class Bar def nullify! update_attribute :foo_id, nil end end 

And now you can call it on any instance of the bar. To make it fit your example, you can do this:

 def remove !self.foo_id.nil? end def remove= bool update_attribute :foo_id, nil if bool end 

This version will allow you to pass a parameter equal to true or false, so you can implement it as a flag in forms. Hope this helps!

UPDATE: I added a blog post that details how non-attributes can be used as form elements in rails, adding accessors to your model:

Dynamic form elements in Ruby on Rails

It includes a working Rails 3 application that shows how all the parts work together.

+6
source

All Articles