rails 4 post#method_missing

时间:2014-05-27 08:50:09

标签: ruby-on-rails ruby devise

我只想将一个user_id添加到帖子的评论中。当我改变一些事情时会得到不同的错误,但所有提供的解决方案都没有帮助我。

我使用RailsApp和Devise。

CommentsController

class CommentsController < ApplicationController  
before_action :authenticate_user!, :except => [:show, :index]  

def index
@comments = Comment.all
end

def new
end

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

if @comment.save
 format.html { redirect_to post_path(@post), notice: 'Comment was successfully created.' }
    format.json { render :show, status: :created, location: @post }
  else
    format.html { render :new }
    format.json { render json: @comment.errors, status: :unprocessable_entity }
  end
end  

private
# Use callbacks to share common setup or constraints between actions.
def set_comment
  @comment = Comment.find(params[:id])
end

def set_user
  @user = current_user
end

# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
  params.require(:comment).permit(:body, :post_id, :user_id)
end
end

附加:
在RSB提供更改后,我仍然遇到错误(参数太少)。我改变了控制器,现在它工作。

if @comment.save
respond_to do|format|
format.html { redirect_to post_path(@post)}
    format.json { render :show, status: :created, location: @post }
  end
 end
end

1 个答案:

答案 0 :(得分:0)

将帖子和评论之间的关联设为has_many,并假设user_id表格中存在comments列,请执行此操作

@comment = @post.comments.new(comment_params)
@comment.user_id = current_user.id