Creating named relations in Rails 3 models
I'm trying to learn Rails and I'm struggling to understand how self relations are declared using the ActiveRecord component.
If I have someth开发者_如何学运维ing like this:
class Comment < ActiveRecord::Base
has_many :comments
belongs_to :comments
end
Being the related comments the comment's replies and the comment's parent, how am I supposed to access them if they have the same name? I can't just do comment.comments
, they would need to have different names.
Thanks.
For one, belongs_to
is a singular association, so it would be:
belongs_to :comment
... and you would have no name conflict.
But for cases where you do have conflicts, you can always rename relations, for example:
has_many :comments
has_many :recent_comments, :class_name => 'Comment', :limit => 10, :order => 'id DESC'
See more examples of options for associations in the docs.
You need to use singular for belongs_to
associations:
belongs_to :comment
It looks like you are trying to create a tree-like structure of Comment
s. You might want to take a look at gems like paginary.
The first symbol passed to the has_many method is the name you want to specify. Rails uses the Convention over configuration principle, so it takes the related class' name from it to, but you can specify it like this:
has_many :rel, :class_name => "Class"
精彩评论