Rajat
Rajat

Reputation: 105

ForbiddenAttributesError in Rails 5

I am getting Forbidden Attributes Error even though I have used strong parameters in Rails. I have two models: Posts and Categories. Here is my Post Controller: class PostsController < ApplicationController def index @posts=Post.all end

def new
    @post=Post.new
    @category=Category.all
end

def create
    @post = Post.new(params[:post])
    if @post.save
        redirect_to posts_path,:notice=>"Post saved"
    else
        render "new"
    end
end

def allowed_params
    params.require(:post).permit(:title, :body, :category_id)
end 

end

And here is my view for posts/new:

<%= form_for @post do |f| %>
    <p>
        <%= f.label :title %></br>
        <%= f.text_field :title%><br/>
    </p>
    <p>
        <%= f.label :body %></br>
        <%= f.text_area :body%><br/>
    </p>
    <p>
        <%= f.select :category_id, Category.all.collect{|x| [x.name,x.id]},{:include_blank =>"Select one"}%><br/>
    </p>
    <p>
        <%= f.submit "Add Post" %>
    </p>
<% end %>

But I am still getting Error.

Upvotes: 1

Views: 3383

Answers (1)

Thanh
Thanh

Reputation: 8624

You need to use allowed_params instead of params[:post]:

@post = Post.new(allowed_params)

Upvotes: 3

Related Questions