我尝试创建博客,我有3个模型post
,user
,comment
。当我创建comment
时,comment.post_id
为nil
。我做错了什么?
comments_controller
def new
@comment = Comment.new
end
def edit
@post = Post.find(params[:post_id])
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
@comment.user_id = current_user
redirect_to post_path(@post)
end
修改的
post.rb
has_many :comments, dependent: :destroy
belongs_to :user
comment.rb
belongs_to :user
belongs_to :post
user.rb
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
答案 0 :(得分:0)
这是解决方案:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new(params[:comment])
@comment.user_id = current_user.id
@comment.save
redirect_to post_path(@post)
end
因此,请在上面的源代码中使用以下关联。
答案 1 :(得分:0)
希望这会奏效。
def create
@post = Post.find(params[:post_id])
@comment = Comment.new(comment_params.merge(user_id: current_user.id))
@post.comments << @comment
redirect_to post_path(@post)
end