i76 webdesign, Sittard
Ruby on Rails Association Extensions
Imagine a user that has a inbox full of messages, now somewhere in your application, you want to get the number of unread messages. You could do a bit of sql, but isn’t this nicer?
class User < ActiveRecord::Base
has_many :messages,
:foreign_key => 'receiver_id' do
def unread
find :all, :conditions => ['viewed_at is null']
end
end
end
Now you can use User.find(:first).messages.unread to get the unread messages of the first user.
These kinds of methods are called Association Extensions and you can read more about them on the associations documentation page.