How to use attr_accessible (maybe there is an equivalent) in Rails 5? The heme protected_attributes does not work, as there is a conflict with the activemodel and activerecord versions. Thank you in advance.

    1 answer 1

    This attribute does not work in modern versions of the Ruby on Rails framework. Previously, it was used to explicitly specify the attributes that can be "mass" edited at the controller level (that is, in the group of parameters that come from the form). This practice is recognized as unsuccessful, firstly, you implicitly allow editing for all controllers, which can be many (at least the application and the administration system), secondly, you explicitly issue permissions at the model level, which should be issued at the controller level. Thirdly, too free use of this attribute (for both backend and frontend parts of the application) resulted in application vulnerabilities, when using frontend parts it was possible to change the parameters of the model that are not allowed to change from the frontend parts but which were allowed in attr_accessible for example for the backend part of the site.

    Starting with Ruby on Rails 4, to allow parameter assignments of the current model, it was moved from the model level to the controller level. Now you need to explicitly specify which parameters are allowed to change in the model at the controller level. For example, one of the possible options might look like this.

     class SomeController < Admin::ApplicationController ... def create resource = Resourse.new resource.assign_attributes(resoure_params) if resource.save redirect_to index_page else render resource.new_record? ? :new : :edit end end ... private def resourse_params [ :id, :name, :weight ] end ... end 

    or you can explicitly go through the parameters, mark using the method of permit those that can be transferred to the model and use for example the create method

     class SomeController < Admin::ApplicationController ... def create if Resourse.create resource_params redirect_to index_page else render resource.new_record? ? :new : :edit end end ... private def resource_params params.require(:resource).permit(:id, :name, :weight) end ... end 
    • Thank you for the full, useful and detailed answer) - Sklerozz