gpt4 book ai didi

ruby-on-rails - 一个模型可以属于多个模型吗?

转载 作者:行者123 更新时间:2023-12-05 00:05:52 24 4
gpt4 key购买 nike

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

最佳答案

是的,你可以,而且你不需要指定外键或类名来这样做。说 belongs_to :user意味着 rails 将在 comments 表中查找 user_id 整数字段,并期望存在名为 User 的 ActiveRecord 类。

随意添加,它们不会相互干扰。

关于ruby-on-rails - 一个模型可以属于多个模型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4036779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com