一个模型可以属于多个模型吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以,并且不需要指定外键或类名来执行此操作。说
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.