Search code examples
ruby-on-railsruby-on-rails-4strong-parameters

Rails 4 - ActiveModel::ForbiddenAttributesError


I have read other issues about it, but still I can't point what is causing the error. I have defined the strong parameters of Rails 4, but it keeps showing the error:

ActiveModel::ForbiddenAttributesError in MessagesController#create

My view is this:

<%= form_for(@message) do |f| %>
    <div class="form-group field">
  <%= f.label :phrase %>
  <br/>
  <%= f.text_field :phrase,  autofocus: true, class: 'form-control' %>
</div>
<div class="form-group field">
  <%= f.label :date %>
  <br/>
  <%= f.date_field :date, class: 'form-control' %>
</div>
<div class="actions text-center">
  <%= f.submit "Submit", class: 'btn btn-default' %>
</div>
<% end %>

My controller:

class MessagesController < ApplicationController

def today
    @dates = Message.all()
end

def history
    @messages = Message.history_checker
end

def new
    @message = Message.new
end

def create
    @message = Message.new(params[:message])
    if @message.save
        flash[:notice] = "OK"
        redirect_to root_path
    else
        render :action => 'new'
    end
end

private

def message_params
  params.require(:message).permit(:phrase,:date)
end 
end

The error points to line 15 of controller @message = Message.new(params[:message]). Any ideas?


Solution

  • You just need to use message_params instead of params[:message]:

    @message = Message.new(message_params)