Rails:如果 has_many 关系改变了 [英] Rails: if has_many relationship changed

查看:35
本文介绍了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_many 关系改变了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆