Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is touch for a belongs_to in Rails triggered?

Tags:

I have a question-and-answer app. Every time someone adds an answer to a question, I want to update the updated_at timestamp on the question.

Therefore I'm using touch in the Answer model.

  belongs_to :question, :touch => true 

However, it seems that the timestamp is updating at when there are no answers being added. I am trying to figure out how/why. This has only been happening since adding this touch method.

So I wanted to confirm when touch is fired? Is it only when an answer object is created, edited or destroyed? Are there any other events? i.e. It should not be triggered just by looking at an answer object under particular circumstances?

I couldn't find any solid documentation describing how touch exactly works in the context of a belongs_to relationship.

The reason this is a bit puzzling is that the app is relatively simple and does not give the user any functionality for editing or destroying answers once submitted.

like image 268
bigwinner Avatar asked Dec 19 '12 13:12

bigwinner


People also ask

What does touch do in Rails?

In rails touch is used to update the updated_at field for persisted objects. But if we pass other attributes as arguments, it will update those fields too along with updated_at . Even it will update non-date-time fields if passed as arguments.

What is touch true?

:touch If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or destroyed. If you specify a symbol, that attribute will be updated with the current time in addition to the updated_at/on attribute. belongs_to :company, :touch => true.


1 Answers

From: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

:touch If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or destroyed. If you specify a symbol, that attribute will be updated with the current time in addition to the updated_at/on attribute.

belongs_to :company, :touch => true

belongs_to :company, :touch => :employees_last_updated_at

like image 109
wpp Avatar answered Sep 18 '22 22:09

wpp