Rails嵌套模型 - 删除关联

Soo*_*uNe 4 ruby-on-rails nested-attributes

什么相当于<%= f.hidden_field :_destroy %>nullify而不是毁灭?(即我只是将它从关联中删除,但我不想破坏它).

一个示例情况是:

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
Run Code Online (Sandbox Code Playgroud)

在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 %>
Run Code Online (Sandbox Code Playgroud)

对解决方案的一个小修改

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

所以现在我可以调用.edit.html:

<%= builder.hidden_field :_remove %>
Run Code Online (Sandbox Code Playgroud)

Jai*_*yer 6

创建一个这样的方法:

class Bar
  def nullify!
    update_attribute :foo_id, nil
  end
end
Run Code Online (Sandbox Code Playgroud)

现在你可以在任何一个bar实例上调用它.为了使它适合您的示例,您可以这样做:

def remove
  !self.foo_id.nil?
end

def remove= bool
  update_attribute :foo_id, nil if bool
end
Run Code Online (Sandbox Code Playgroud)

此版本将允许您传入一个等于true或false的参数,因此您可以将其实现为表单中的复选框.我希望这有帮助!

更新:我添加了一篇博文,通过向模型添加访问器,更详细地介绍了如何将非属性用作rails中的表单元素:

Ruby on Rails中的动态表单元素

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