将用户 ID 分配给嵌套模型

Assigning a User Id to a Nested Model

将 Rails 4 与 Devise

结合使用

我有一个 Post 模型和一个 Comment 模型。评论嵌套在 Post 中。我已将帖子分配给用户,但由于它是嵌套的,因此无法将评论分配给用户。

routes.rb

resources :posts do
  resources :comments
end

user.rb

has_many :posts
has_many :comments

post.rb:

has_many :comments
belongs_to :user

comment.rb:

belongs_to :post
belongs_to :user

在我的 comments_controller.rb 中,我试过这样使用 current_user:

def new
  post = Post.find(params[:post_id]
  @comment = current_user.post.comments.build

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @comment }
  end
end

def create
    post = Post.find(params[:post_id])
    @comment = current_user.post.comments.create(comment_params)

    respond_to do |format|
      if @comment.save
        format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
        format.xml  { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

但我收到此错误:

undefined method `post' for #<User:0x00000103300a30>

解决此问题的最佳方法是什么?

@comment = post.comments.build

而不是

@comment = current_user.post.comments.build

不是这样的。

您已经告诉它 post 是什么,所以您希望 current_user.post 到 return 有什么不同吗?

def create
  post = Post.find(params[:post_id])
  @comment = post.comments.create(comment_params)
  @comment.user = current_user

  respond_to do |format|
    if @comment.save
      format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
      format.xml  { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
    end
  end
end

而不是

def create
  post = Post.find(params[:post_id])
  @comment = current_user.post.comments.create(comment_params)

  respond_to do |format|
    if @comment.save
      format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
      format.xml  { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
    end
  end
end