2014-01-12 82 views
0

我對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.

回答

0

您從params屬性,讀取針對Post:name, :title, :context),但你需要閱讀Comments屬性(:commenter, :body

替換此:

@comment = post.comments.create(params[:comment].permit(:name, :title, :context))

@comment = post.comments.create(params[:comment].permit(:commenter, :body))

,或者更好的,有:

@comment = post.comments.create(comment_params)

0

看來,你是明確permitting不同組在create行動屬性。

您應該更新您的create操作,以使用comment_params,就像您在update操作中所做的那樣。原因是您的Comment絕對是您期望的CommenterBody,而不是您在create行動中允許的:name, :title, :context

更新controllercreate行動:

# POST /comments 
    # POST /comments.json 
    def create 
    ... 
    @comment = post.comments.create(comment_params) 
    ... 
    end 
+0

這不起作用:ActiveRecord的:: AssociationTypeMismatch在CommentsController#創建 郵政(#35862540)預期,得到了字符串(#15668268) – PJDW

+0

當我在評論中改變了我的參數時,它也工作。所以thx很多! – PJDW