Franco
Franco

Reputation: 905

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 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

Answers (3)

alcuadrado
alcuadrado

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

numbers1311407
numbers1311407

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

rdvdijk
rdvdijk

Reputation: 4398

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 Comments. You might want to take a look at gems like paginary.

Upvotes: 0

Related Questions