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

发布于 2024-09-29 05:13:36 字数 355 浏览 0 评论 0原文

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

那么通过上述关联,我可以从给定的评论对象中获取用户和帖子详细信息吗?。
另请注意

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

,我已使用评论作为帖子的嵌套资源。

resources :posts do  
   resources :comments  
end  
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  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹉夏雨初晴づ 2024-10-06 05:13:37

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文