Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: if has_many relationship changed

Tags:

I've got these two classes.

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 

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.

like image 572
t56k Avatar asked May 24 '13 03:05

t56k


2 Answers

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... 

Or you can use Enumerable#any?:

if @doc.articles.any? {|a| a.changed?} then... 
like image 69
lurker Avatar answered Sep 28 '22 07:09

lurker


Use the after_add and after_remove association callbacks to check for additions/removals along with using saved_changes? to check for any changes on existing articles.

class Doc < ActiveRecord::Base   has_many :articles, after_add: :set_article_flag, after_remove: :set_article_flag    after_save :do_something_with_changed_articles    private    def set_article_flag     @articles_changed = true   end    def do_something_with_changed_articles     if @articles_changed || articles.any?(&:saved_changes?)       # do something     end   end end 
like image 36
akaspick Avatar answered Sep 28 '22 07:09

akaspick