Hemanth
Hemanth

Reputation: 5145

Can a model belong_to more than one model?

class Comment < ActiveRecord::Base  
  belongs_to :post  
  belongs_to :user  
end  

So with the above association can I fetch both user and post details from a given comment object?.
like

@comment.post.post_title and  
@comment.user.user_name.  

Also please note that I have used comment as a nested resource of post.

resources :posts do  
   resources :comments  
end  

Upvotes: 4

Views: 813

Answers (1)

Jaime Bellmyer
Jaime Bellmyer

Reputation: 23317

Yes you can, and you don't need to specify the foreign key or class name to do so. Saying belongs_to :user means rails will look for a user_id integer field in the comments table, and expect an ActiveRecord class named User to exist.

Add as many as you like, they don't interfere with each other.

Upvotes: 7

Related Questions