Cyzanfar
Cyzanfar

Reputation: 7136

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?

Upvotes: 0

Views: 56

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

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).

Upvotes: 2

Related Questions