【发布时间】:2016-03-01 11:00:32
【问题描述】:
具有以下关联:
class User < ActiveRecord::Base
has_many :posts
has_many :comments
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
我可以在控制器中做这样的事情:
@comment = current_user.comments.new(comment_params)
@comment.user
但要访问关联的Post,我需要手动设置它的父级:
@comment.post = Post.find params[:post_id]
当创建一个新的Comment 时,有没有更好的方法来做到这一点?
【问题讨论】:
-
你的资源是嵌套的吗?看起来他们是。
-
不,他们还没有。
-
你能提供你的架构供用户发帖和评论吗?
-
belongs_to方法仅应在此类包含外键时使用。那么你的Comment模型中有user_id和post_id吗? -
@AzatGataoulline 是的,我有。
标签: ruby-on-rails ruby activerecord associations