Strong Parameters & Rails 4

Today I was doing some Rails training on Treehouse. As I was working on my demo app I got the message:

`attr_accessible` is extracted out of Rails into a gem. Please use new recommended protection model for params(strong_parameters) or add `protected_attributes` to your Gemfile to use old one.

So I did some googling and here is one of the posts (quick & dirty) that I liked more about this new mode of operation.

http://blog.remarkablelabs.com/2012/12/strong-parameters-rails-4-countdown-to-2013

in three words….

This (before)…

Here is an example of how you would allow mass assignment of name and age for a Person model in Rails 3:

class PeopleController < ApplicationController
  ...
  def create
    @person = Person.create(params[:person])
    ...
  end
  ...
end

You would have to whitelist both :name and :age in your model usingattr_accessible:

class Person < ActiveRecord::Base
  attr_accessible :name, :age
end

… goes to this (After)

In Rails 4, you don’t need to whitelist attributes in your model anymore. In your controller you can filter the params as you see fit:

class PeopleController < ApplicationController
  ...
  def create
    @person = Person.create(person_params)
    ...
  end
  ...
  private
    def person_params
      params.require(:person).permit(:name, :age)
    end
end

Intresting… so most of those tutorials should change…


George Psistakis

I love technology and working with people. That is why I am trying to offer as much as I can at the local startup ecosystem and at the same time building Apirise. A platform to reduce time and effort required to integrate and maintain APIs. Simply, fast and efficiently!
I am co-organizer of the Agile Greece and API Athens meetups and I contribute at the Developer Economics Blog.


Discuss with me…

I’d love to know your ideas and thoughts on this post.
Connect with me on Twitter or Google+

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s