简体   繁体   中英

ActiveModel::ForbiddenAttributesError Rails 4.1

I'm getting the following ActiveModel::ForbiddenAttributesError when creating a comment on my app.

The error message precise that the problem comes from line 7 in my Comments Controller file: @comment = @pin.comments.create(params[:comment])

app/controllers/comments_controller.rb

class CommentsController < ApplicationController

  before_filter :authenticate_user!

  def create
    @pin = Pin.find(params[:pin_id])
    @comment = @pin.comments.create(params[:comment])

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @pin, notice: 'Comment was successfully created.' }
        format.json { render json: @comment, status: :created, location: @comment }
      else
        format.html { render action: "new" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end

  end

  private
  def comment_params
      params.require(:comment).permit(:body, :pin_id)
    end


end

here is the comment model

class Comment < ActiveRecord::Base

      belongs_to :pin

end

Any help with this error message?

You should replace this line with

@comment = @pin.comments.create(comment_params)

Also, putting pin_id in permitted parameters is unnecessary (since you create comment through @pin.comments association) and possibly unsafe (user could associate comment with other Pin ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM