开发者

Rails Nested Model - Remove Association

开发者 https://www.devze.com 2023-01-29 03:55 出处:网络
What\'s the equivalent to <%= f.hidden_field :_destroy %> for nullify instead of destroying? (i.e I just was to remove it from the association, but I don\'t want to destroy it).

What's the equivalent to <%= f.hidden_field :_destroy %> for nullify instead of destroying? (i.e I just was to remove it from the association, but I don't want to destroy it).

An example situation would be:

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's 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 modification to the solution

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 in .edit.html:

<%= builder.hidden_field :_remove %>


Create a method like this:

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

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

def remove
  !self.foo_id.nil?
end

def remove= bool
  update_attribute :foo_id, nil if bool
end

This version will let you pass in a parameter that equates to true or false, so you can implement it as a checkbox in forms. I hope this helps!

UPDATE: I've added a blog post that goes into more detail about how non-attributes can be used as form elements in rails, by adding accessors to your model:

Dynamic Form Elements in Ruby on Rails

It includes a working Rails 3 sample app to show how all the parts work together.

0

精彩评论

暂无评论...
验证码 换一张
取 消