How is attr_accessible used in Rails 4? How is attr_accessible used in Rails 4? ruby-on-rails ruby-on-rails

How is attr_accessible used in Rails 4?


Rails 4 now uses strong parameters.

Protecting attributes is now done in the controller. This is an example:

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

No need to set attr_accessible in the model anymore.

Dealing with accepts_nested_attributes_for

In order to use accepts_nested_attribute_for with strong parameters, you will need to specify which nested attributes should be whitelisted.

class Person  has_many :pets  accepts_nested_attributes_for :petsendclass PeopleController < ApplicationController  def create    Person.create(person_params)  end  # ...  private  def person_params    params.require(:person).permit(:name, :age, pets_attributes: [:name, :category])  endend

Keywords are self-explanatory, but just in case, you can find more information about strong parameters in the Rails Action Controller guide.

Note: If you still want to use attr_accessible, you need to add protected_attributes to your Gemfile. Otherwise, you will be faced with a RuntimeError.


If you prefer attr_accessible, you could use it in Rails 4 too.You should install it like gem:

gem 'protected_attributes'

after that you could use attr_accessible in you models like in Rails 3

Also, and i think that is the best way- using form objects for dealing with mass assignment, and saving nested objects, and you can also use protected_attributes gem that way

class NestedForm   include  ActiveModel::MassAssignmentSecurity   attr_accessible :name,                   :telephone, as: :create_params   def create_objects(params)      SomeModel.new(sanitized_params(params, :create_params))   endend


We can use

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method