尝试创建对评论的回复我收到错误
NoMethodError (undefined method `replies' for 52:Integer):
app/controllers/replies_controller.rb:29:in `create'
回复表格
<%= form_with(model: @reply, url: [Comment.find(params[:id]), @reply]) do |form| %>
回复控制器 - 创建
def create
@reply = @comment.replies.create(reply_params).permit(:reply)
respond_to do |format|
if @comment.replies.save
format.html {redirect_to @reply, notice: 'Reply was successfully created.'}
format.json {render :show, status: :created, location: @reply}
else
format.html {render :new}
format.json {render json: @reply.errors, status: :unprocessable_entity}
end
end
end
def set_comment
@comment = Comment.find(reply_params[:post_id]).id
end
schema.rb
create_table "replies", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "anonymous"
t.text "text"
t.integer "user_id"
t.integer "post_id"
t.string "title"
end
的routes.rb
resources :comments do
resources :replies
end
我认为问题可能是架构。 我见过类似的例子有t.references:comment,index:true,foreign_key:true在他们的回复表中
答案 0 :(得分:0)
您正试图从id:
获取关联对象@comment = Comment.find(reply_params[:post_id]).id
你需要一个对象:
def set_comment
@comment = Comment.find(reply_params[:post_id])
end
<强>更新强>
更正控制器示例:
def create
@comment = Comment.find(reply_params[:post_id]) #In fact, it should look like this - params[:comment_id]
@reply = @comment.replies.new(reply_params)
respond_to do |format|
if @reply.save
format.html { redirect_to @reply, notice: 'Reply was successfully created.' }
format.json { render :show, status: :created, location: @reply }
else
format.html { render :new }
format.json { render json: @reply.errors, status: :unprocessable_entity }
end
end
end
private
def reply_params
params.require(:reply).permit(...) #Model attributes
end