Rails 3. Get the Latest Update

I am developing an API using Rails 3. A user can have several contact elements, such as phones, emails, websites and an address. Each element received its own model.

I need to do caching in my iPhone application using this API, so I need to get the date when the last update occurred in any of the elements and is mapped to the timestamp of the cache file.

How can I get the most updated elements (when comparing all element tables)?

I get the very last item for every item table like this. Is that really good?

@phones = @user.phones.order("updated_at desc").limit(1) 

Thanks for the help!

+6
source share
1 answer

You can use the ActiveRecord touch method. This is especially useful if you have one parent record with many child records. Each time child records are saved or destroyed, the parent record will have the updated_at field set to the current time.

 class User < ApplicationRecord has_many :phones has_many :addresses end class Phone < ApplicationRecord belongs_to :user, touch: true end class Address < ApplicationRecord belongs_to :user, touch: true end 

At any time when the address or phone is updated, the user updated_at will be set to the current time.

To check when the last update for the current user occurred in all of its tables, follow these steps:

 @last_updated = @user.updated_at 

For small recording overheads, you get many benefits with simpler queries when checking the validity period of your cache. The documentation on this subject can be found in the section belongs to the parameters .

+13
source

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


All Articles