Friday, May 30, 2008

To be singular or to be plural

ActiveRecord's relationship is sensitive to the plurality of the database table name.

Let's say, blogs contains many posts, then blogs should be on singular side and posts on plural side.


class Blog < ActiveRecord::BASE
has_many :posts #a plural declare
end


class Post < ActiveRecord::BASE
belongs_to :blog #a singular declare
end


For has_one and belongs_to relationship, it should be singular. Suppose each user has only one avatar:


class Avator < ActiveRecord::BASE
belongs_to :user #a singular declare
end


class User < ActiveRecord::BASE
has_one :avatar #a singular declare
end


If you don't follow the convention, it won't work.

No comments: