How to update a model's "updated_at" field only for a subset of column updates?
activerecord, data-modeling, ruby-on-rails, ruby-on-rails-3
Solution
Two approaches spring to mind:
Don't use `:updated_at` for the purpose you are using it for. Instead create a new column, say `:post_updated_at`, and update it manually on each save that you want to cause the post to move to the top. Rails provides a convenient model mehod for this:
mypost.touch :post_updated_at
When you are updating a column and want `:updated_at` to remain untouched, use the `#update_column` method, which directly updates the column in the database with the value you give it. Note that it writes the value to the database verbatim, so you will have to be clever if the column in question is a fancy `serialize` column or similar.
Problem
There is a typical blog application. Each user has_many posts. Each post has_many tags. I'm sorting each post by updated_at so the most recently updated post will show up on top. So for example, if I update a post's content, the post will come up to the top. However, this also happens when I just add a tag, since a tag is connected to its corresponding post. I only want the content update to change updated_at field. I don't want updated_at for a post to be changed because I added a tag. Is there a way to do this? Or any other way to achieve something like this? Thank you!