什么等同于 <%= f.hidden_field :_destroy %>
取消而不是销毁? (即我只是想将它从协会中删除,但我不想破坏它)。
一个示例情况是:
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 %>
最佳答案
创建一个这样的方法:
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 中的表单元素:
Dynamic Form Elements in Ruby on Rails
它包括一个可运行的 Rails 3 示例应用程序,以展示所有部分如何协同工作。
关于ruby-on-rails - Rails 嵌套模型 - 删除关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4382969/