How to "touch" the parent model of the own_to association only if certain conditions are met?

I use Rails 3.1.0, and I would like to “touch” the parent model of the belongs_to association only if certain conditions are met.

For example, at this time I:

 belongs_to :article, :touch => true 

I would “touch” the parent model only if it is “publicly available”. That is, the Article class has an attribute called access ( @article.access => public or private ), and I would like to check this value before touching it: if this value is not public , then tap it!

Can this be done “directly” in the belongs_to association belongs_to ? If so, how?

+6
source share
2 answers

You can try lambda as you said, but I'm not sure if this will work. Something like that:

 belongs_to :article, :touch => Proc.new{|o| o.article && o.article.public } 

According to the implementation , maybe you can try to return nil instead of false in proc when it is not available

 belongs_to :article, :touch => Proc.new{|o| o.article && o.article.public ? true : nil } 

If this does not work, use before storing the callback as follows:

 class Model < ActiveRecord::Base belongs_to :article before_save :touch_public_parent def touch_public_parent article.touch if article && article.public? end end 

Let me know if you have any questions.

Update # 1

Relevant part from add_touch_callbacks :

 if touch_attribute == true association.touch unless association.nil? else association.touch(touch_attribute) unless association.nil? end 

So, if you pass true, then just touch the updated_at attribute. If you pass a field name, it will update that field if you do not pass nil . If you pass nil, nothing updates. That's why I said that maybe you can try the second version of the belongs_to association.

+4
source

I don’t think you can apply a touch to a condition in the belongs_to association.

There is a way that is a bit hacked but will work directly with the belongs_to association,

This may not be the recommended method.

  class YourModel
   belongs_to: article
   belongs_to: public_article,: class_name => "Article", 
              : foreign_key => "article_id", 
              : conditions => {: public => true},: touch => true 
 end 
0
source

Source: https://habr.com/ru/post/906029/


All Articles