将用户ID分配给嵌套模型

时间:2015-05-16 02:09:08

标签: ruby-on-rails ruby ruby-on-rails-4 devise

将Rails 4与Devise一起使用

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

的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>

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

@comment = post.comments.build

而不是

@comment = current_user.post.comments.build

它没有那样的工作。

您已经告诉它post是什么,您期望current_user.post返回不同的内容吗?

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