我對Ruby on Rails很陌生,而且我正在用腳手架控制器掙扎。 我做了一個嵌套的資源,我的評論放置在帖子中。未保存Rails窗體參數
控制器的簡化版本是
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# omited new, index, show...
# POST /comments
# POST /comments.json
def create
post = Post.find(params[:post_id])
@comment = post.comments.create(params[:comment].permit(:name, :title, :context))
respond_to do |format|
if @comment.save
format.html { redirect_to([@comment.post, @comment], notice: 'Comment was successfully created.') }
format.json { render action: 'show', status: :created, location: @comment }
else
format.html { render action: 'new' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
post = Post.find(params[:post_id])
@comment = post.comments.find(params[:comment])
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:commenter, :body, :post)
end
end
當我填寫表格,我得到這個例外:被保存禁止此評論
2個錯誤: 批評家不能爲空 正文不能爲空
我試圖this指導,但我認爲這是使用Rails不是100%兼容4.
這不起作用:ActiveRecord的:: AssociationTypeMismatch在CommentsController#創建 郵政(#35862540)預期,得到了字符串(#15668268) – PJDW
當我在評論中改變了我的參數時,它也工作。所以thx很多! – PJDW