为什么user_id没有分配comment_id?

时间:2015-02-23 16:57:02

标签: ruby-on-rails

我尝试创建博客,我有3个模型postusercomment。当我创建comment时,comment.post_idnil。我做错了什么?

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

2 个答案:

答案 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

来源:Answer in stackoverflow

因此,请在上面的源代码中使用以下关联。

答案 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