开发者

Creating named relations in Rails 3 models

开发者 https://www.devze.com 2023-04-08 17:43 出处:网络
I\'m trying to learn Rails and I\'m struggling to understand how self relations are declared using the ActiveRecord component.

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 Comments. 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"
0

精彩评论

暂无评论...
验证码 换一张
取 消