模型可以属于多个模型吗?

Hem*_*nth 4 nested ruby-on-rails associations

class Comment < ActiveRecord::Base  
  belongs_to :post  
  belongs_to :user  
end  
Run Code Online (Sandbox Code Playgroud)

因此,通过上述关联,我可以从给定的评论对象中获取用户和帖子详细信息吗?
喜欢

@comment.post.post_title and  
@comment.user.user_name.  
Run Code Online (Sandbox Code Playgroud)

另请注意,我已将评论用作帖子的嵌套资源.

resources :posts do  
   resources :comments  
end  
Run Code Online (Sandbox Code Playgroud)

Jai*_*yer 7

是的,您可以,并且您不需要指定外键或类名来执行此操作.Saying belongs_to :user意味着rails将在comments表中查找user_id整数字段,并期望存在名为User的ActiveRecord类.

添加任意多个,它们不会相互干扰.