Can a model belong to more than one model?

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

So, with the above link, can I get both user data and messages from this comment object ?.

as

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

Also note that I used the comment as an attached message resource.

 resources :posts do resources :comments end 
+4
source share
1 answer

Yes, you can, and you do not need to specify a foreign key or class name for this. The statement belongs_to :user means that the rails will look for the integer field user_id in the comment table and expect the ActiveRecord class named User to exist.

Add as much as you want, they do not interfere with each other.

+7
source

All Articles