Rails: if has_many relationship changed

后端 未结 5 1525
借酒劲吻你
借酒劲吻你 2021-01-01 15:21

I\'ve got these two classes.

class Article < ActiveRecord::Base
  attr_accessible :body, :issue, :name, :page, :image, :video, :brand_ids
  has_many :pub         


        
5条回答
  •  执念已碎
    2021-01-01 15:39

    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
    

提交回复
热议问题