Rails3中如何删除嵌套对象?
如何删除表单中的嵌套对象?我发现我需要在父模型的accepts_nested_attributes_for 指令中添加:allow_destroy
。
此外,我想限制删除。如果父对象是唯一保留关联的对象,则仅应删除嵌套对象。
示例:
class Internship < ActiveRecord::Base
belongs_to :company
accepts_nested_attributes_for :company, allow_destroy => true
end
class Company < ActiveRecord::Base
has_many :internships
end
说明:一家公司可以举办多次实习。因此,只要至少有一项其他实习与之相关,我就不想删除该公司记录。
How can I delete nested objects in a form? I found out that I need to add :allow_destroy
in the parent model at the accepts_nested_attributes_for
directive.
Further, I want to restrict the deletion. A nested object only should be deleted, if the parent object is the only one that retains the association.
Example:
class Internship < ActiveRecord::Base
belongs_to :company
accepts_nested_attributes_for :company, allow_destroy => true
end
class Company < ActiveRecord::Base
has_many :internships
end
Explanation: A company can host many internships. Therefore, I do not want to delete the company record as long as there is at least one other internship associated with it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 dependent => :破坏
You could use dependent => :destroy
如果您在
before_destroy
过滤器中返回 false,则销毁操作将被阻止。因此我们可以检查是否有与该公司相关的实习机会,如果有则阻止。这是在公司模型中完成的。If you return false in a
before_destroy
filter, then the destroy action will be blocked. So we can check to see if there are any internships associated to the company, and block it if so. This is done in the company model.