How is attr_accessible used in Rails 4?

前端 未结 5 969
执笔经年
执笔经年 2020-11-22 08:36

attr_accessible seems to no longer work within my model.

What is the way to allow mass assignment in Rails 4?

5条回答
  •  死守一世寂寞
    2020-11-22 09:05

    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)
      end
    end
    

    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 :pets
    end
    
    class PeopleController < ApplicationController
      def create
        Person.create(person_params)
      end
    
      # ...
    
      private
    
      def person_params
        params.require(:person).permit(:name, :age, pets_attributes: [:name, :category])
      end
    end
    

    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.

提交回复
热议问题