Friday, May 30, 2008

The one I love most

If a Model class has a "has_many" relationship available, it can specify a "has_one" relationship pointing to one record for future convenient reference.

:conditions and other SQL options can be used to narrow the search.

Blog has many Post


class Blog < ActiveRecord::BASE
has_many :posts #has_many must be present
has_one :first_post, #no naming convention.
:class_name => 'Post', #must specify!
:order => 'created_at asc'
end

class Post < ActiveRecord::BASE
belongs_to :blog #one belongs_to is enough
end


Later, you can reference the first record easily by:

>>blog1 = Blog.find :first
>>blog1.first_post


Yes! this is the one I love most, give her some special treat.

No comments: