Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3. Get most recent update

I am developing an API using Rails 3. A user can have several contact items, like phones, emails, websites and address. Each item got its own model.

I need to do caching in my iPhone app that is using this API therefore I need to get the date when the latest update to any of the items occured and match it against the timestamp of the cache file.

How can I get the most updated items (when comparing all the item tables)?

I am getting the most recent item for each item table like this. Is this really good?

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

Thankful for all help!

like image 829
Jonathan Clark Avatar asked Jun 30 '11 09:06

Jonathan Clark


1 Answers

You can make use of ActiveRecord's touch method. This is especially useful if you have one parent record with many child records. Every time the child records are saved or destroyed the parent record will have it's 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

Now any time an address or a phone is updated, the User's updated_at will be set to the current time.

To check when the last updated for the current user took place, over all their tables, you now do:

@last_updated = @user.updated_at

For a small overhead in writes you gain a lot with simpler queries on checking your cache expiry. The documentation for this can be found under belongs_to options.

like image 145
Douglas F Shearer Avatar answered Nov 12 '22 09:11

Douglas F Shearer