2014-01-12 2 views
0

Я очень новичок в Ruby on Rails, и я борюсь с моим контроллером леса. Я сделал вложенный ресурс, где мои комментарии размещены в сообщениях.Параметры формы Rails не сохраняются

class Post < ActiveRecord::Base 
    validates :name, :presence => true 
    validates :title, :presence => true, :length => { :minimum => 5 } 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    validates :commenter, :presence => true 
    validates :body, :presence => true  
    belongs_to :post 
end 

Упрощенная версия контроллера

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 ошибки запрещенную этот комментарий от спасаемых: Commenter не может быть пустым Кузов не может быть пустым

Я попытался this руководство, но я думаю, что это не 100% совместим с Rails 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 определенно ожидает Commenter и Body, а не :name, :title, :context, который вы разрешили в своем действии create.

Update controller «s create действия как:

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

Это не работает: ActiveRecord :: AssociationTypeMismatch в CommentsController # создать сообщение (# 35862540) ожидается, получил String (# 15668268) – PJDW

+0

Когда я изменил свои параметры в комментарии, это тоже работает. Так и thx много! – PJDW

Смежные вопросы