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.
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.
: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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With