有点晚了,但是对于正在寻找类似解决方案的其他人,您可以通过这种方式检测关系(也有 has_and_belongs_to_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
after_initialize :initialize_article_changes_safe
after_save :change_articles
after_save :initialize_article_changes
before_add_for_articles << ->(method,owner,change) { owner.send(:on_add_article, change) }
before_remove_for_articles << ->(method,owner,change) { owner.send(:on_remove_article, change) }
def articles_changed?
@article_changes[:removed].present? or @article_changes[:added].present?
end
private
def on_add_article(article)
initialize_article_changes_safe
@article_changes[:added] << article.id
end
def on_remove_article(article)
initialize_article_changes_safe
@article_changes[:removed] << article.id
end
def initialize_article_changes
@article_changes = {added: [], removed: []}
end
def initialize_article_changes_safe
@article_changes = {added: [], removed: []} if @article_changes.nil?
end
def unchanged_article_ids
self.article_ids - @article_changes[:added] - @article_changes[:removed]
end
def change_articles
do_stuff if self.articles_changed?
do_stuff_for_added_articles unless @article_changes[:added].nil?
do_stuff_for_removed_articles unless @article_changes[:removed].nil?
end
end
添加或删除关系时会触发这两个钩子before_add_for_NAME-OF-RELATION
和。before_remove_for_NAME-OF-RELATION
触发函数(您不能按名称链接函数,您必须通过 lambda 执行)将添加/删除的关系项的 id 添加到@articel_changes
哈希中。保存模型后,您可以在change_articles
函数中通过对象的 id 来处理对象。之后,@articel_changes
哈希将被清除。