Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveModel::ForbiddenAttributesError in PostsController#create

I've started learning Ruby on Rails.

Iam getting below error: ActiveModel::ForbiddenAttributesError in PostsController#create

Here is the code:

posts_controller.rb

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    @post = Post.find params[:id]
  end

  def new
    @post = Post.new
  end

  def create
    @post =  Post.create(params[:post]) // Its showing me error here

    if @post.save
      redirect_to posts_path notice: "Your Post was saved"
    else
      render "new"
    end
  end

end

new.html.erb

<h1> Add a New Post </h1>

<%= form_for @post do |f| %>
  <p>
    <%= f.label :title %><b/>
    <%= f.text_field :title %><b/>
  </p>
  <p>
    <%= f.label :content %><b/>
    <%= f.text_area :content %><b/>
  </p>
    <%= f.submit "Add a New Post" %>
<%  end %>

post.rb

class Post < ActiveRecord::Base
  validates_presence_of :title, :content
end

Please tell me what went wrong. BTW, iam using Rails4

like image 481
user3815806 Avatar asked Dec 06 '25 03:12

user3815806


2 Answers

In rails4 there is strong parameters so you can't do this:

@post =  Post.create(params[:post])

You need

@post =  Post.create(post_params)

Where post_params is a method in your controller:

private

def post_params
  params.require(:post).permit!
end

permit! will permit anything. You can limit it though to what you want to allow for example params.require(:post).permit(:title, :content)

like image 130
j-dexx Avatar answered Dec 08 '25 15:12

j-dexx


You have to use strong params for rails 4 to solve this problem.

Docs: http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

def post_params
  params.require(:post).permit(:title, :content)
end

and in create action use: Post.create(post_params)

You have to use strong params always when you create or update a record.

like image 34
AlexLarra Avatar answered Dec 08 '25 15:12

AlexLarra