Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails' ActiveRecord, what is touch for?

I've heard of Rails' ActiveRecord/ActiveModel having something called "touch". However, I haven't found anything describing the purpose of this functionality.

What does it do, and what is it useful for?

like image 813
Andrew Grimm Avatar asked Jul 28 '15 01:07

Andrew Grimm


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.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

As per the API Documentation, it is a method that only updates the specified timestamps of the model with the current time. So in order to update the updated_at field:

product.touch 

or to update the updated_at and designed_at fields:

product.touch(:designed_at)  

Now, I have never used this method before, but I'd think it would be useful in a situation to "bump" a question (like on Stack Overflow) to the top of a search query without actually changing the contents.

like image 158
Ryan K Avatar answered Oct 12 '22 23:10

Ryan K