开发者

Can a model belong_to more than one model?

开发者 https://www.devze.com 2023-01-22 11:40 出处:网络
class Comment < Acti开发者_C百科veRecord::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?.
class Comment < Acti开发者_C百科veRecord::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  


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.

0

精彩评论

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