i76 webdesign, Sittard

7 september 2010

Weblog Rubrieken

i76 webdesign, Sittard

Ruby on Rails Association Extensions

Geschreven door: Tom-Eric

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.

Laat een reactie achter




XHTML: Je mag deze elementen en attributen gebruiken: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>


i76 webdesign, Sittard
Tel 046 4007004
Fax 046 4009640
E-mail