Rails: if has_many relationship changed

后端 未结 5 1501
借酒劲吻你
借酒劲吻你 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:47

    I found Enumerable#any? helpful with an intermediate step of reverse sorting by id in following manner:

    @doc.articles.sort { |a, b| b.id <=> a.id }.any?(&:changed?)
    

    That sort step helps any? to return early, instead of looping through older article records to find if any change was made.

    For e.g. in my case I had a has_many :event_responders relation and after adding a new EventResponder to the collection, I validated the above to be working in following manner:

    Without using an intermediate sort

    2.2.1 :019 > ep.event_responders.any? { |a| puts a.changes; a.changed? }
    {}
    {}
    {}
    {}
    {"created_at"=>[Thu, 03 Sep 2015 08:25:59 UTC +00:00, Thu, 03 Sep 2015 08:25:59 UTC +00:00], "updated_at"=>[Thu, 03 Sep 2015 08:25:59 UTC +00:00, Thu, 03 Sep 2015 08:25:59 UTC +00:00]}
    => true 
    

    Using an intermediate sort

    2.2.1 :020 > ep.event_responders.sort { |a, b| b.id <=> a.id }.any? { |a| puts a.changes; a.changed? }
    {"created_at"=>[Thu, 03 Sep 2015 08:25:59 UTC +00:00, Thu, 03 Sep 2015 08:25:59 UTC +00:00], "updated_at"=>[Thu, 03 Sep 2015 08:25:59 UTC +00:00, Thu, 03 Sep 2015 08:25:59 UTC +00:00]}
    => true 
    

    Thanks.

提交回复
热议问题