Reputation: 905
I'm trying to learn Rails and I'm struggling to understand how self relations are declared using the ActiveRecord component.
If I have something 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.
Upvotes: 2
Views: 332
Reputation: 8530
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"
Upvotes: 0
Reputation: 34072
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.
Upvotes: 3