本文介绍了Rails:如果 has_many 关系改变了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这两门课.
class Article < ActiveRecord::Base attr_accessible :body, :issue, :name, :page, :image, :video, :brand_ids has_many :publications has_many :docs, :through => :publications end class Doc < ActiveRecord::Base attr_accessible :issue_id, :cover_id, :message, :article_ids, :user_id, :created_at, :updated_at, :issue_code, :title, :template_id has_many :publications, dependent: :destroy has_many :articles, :through => :publications, :order => 'publications.position' has_many :edits, dependent: :destroy accepts_nested_attributes_for :articles, allow_destroy: false end如何编写条件语句来查看更新 @doc 后 @doc.articles 是否发生变化?
How would I write a conditional statement to see if @doc.articles has changed after updating @doc?
if @doc.articles.changed? ... end以上给了我一个错误.我找不到正确的语法.
The above gives me an error. I can't find the correct syntax.
推荐答案你必须检查每一个..changed? 仅适用于单个记录.如果您需要检查整个关联是否至少有一处更改,您可以执行以下操作:
You have to check each one. .changed? only works on a single record. You could do something like this if you need to check the whole association for at least one change:
if @doc.articles.find_index {|a| a.changed?} then...或者你可以使用Enumerable#any?:
if @doc.articles.any? {|a| a.changed?} then...更多推荐
Rails:如果 has
发布评论