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!
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.
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