4

什么相当于<%= f.hidden_field :_destroy %>for 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

在 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 %>

对解决方案的一个小修改

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

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

<%= builder.hidden_field :_remove %>
4

1 回答 1

6

创建一个这样的方法:

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

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

def remove
  !self.foo_id.nil?
end

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

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

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

Ruby on Rails 中的动态表单元素

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

于 2010-12-08T00:17:18.380 回答