Rails:如果 has

编程入门 行业动态 更新时间:2024-10-28 02:21:13
本文介绍了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

本文发布于:2023-10-18 06:01:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1503341.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!