Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.2strong-parameters

Rails 3.2.13 and strong_parameters exceptions


I'm playing around with Rails 3.2.13 and the strong_parameters gem. I wanted to know if I should be getting a raised exception from ActiveModel::ForbiddenAttributes when I'm testing in development?

My Post model has a :title and :content but if I remove :title from permit, I don't get an error but I do get redirected back to the edit page with the flash notice, so it's saved the record. Although, it didn't change the :title, rightfully so. Is this the default behaviour?

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

I wanted to know if I need to do something else to get the raised exception.

Gemfile:

# Gemfile
gem 'rails', '3.2.13'
gem "strong_parameters"

Application config:

# config/application.rb
config.active_record.whitelist_attributes = false

Post model:

# post.rb model
class Post < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection
end

Post Controller:

# post_controller.rb
class PostsController < ApplicationController

  def update
    @post = Post.find(params[:id])
     if @post.update_attributes(post_params)
       redirect_to edit_post_path(@post), flash { success: "Post updated" }
     else
       render "edit"
     end
  end


  private

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

Solution

  • The default configuration is to log the exception in development and test environments, and not even that in production. So what you are seeing is the normal behaviour, the assignment fails silenty.

    To raise an exception you need to change the default in your desired enviroment. For instance, config/environments/development.rb:

    # Raises an error on unpermitted attributes assignment
      config.action_controller.action_on_unpermitted_parameters = :raise  # default is :log
    

    Hope that helps,