Rails 嵌套模型 - 删除关联
相当于 nullify 而不是 destroy 的 <%= 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 %>
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 %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一个像这样的方法:
现在您可以在任何 bar 实例上调用该方法。为了使其适合您的示例,您可以这样做:
此版本将允许您传递等于 true 或 false 的参数,因此您可以将其实现为表单中的复选框。我希望这有帮助!
更新:我添加了一篇博客文章,详细介绍了如何通过向模型添加访问器将非属性用作 Rails 中的表单元素:
Ruby on Rails 中的动态表单元素
它包含一个工作 Rails 3 示例应用程序来展示所有部分如何协同工作。
Create a method like this:
And now you can call that on any bar instance. To make it fit your example, you could do this:
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.