How does attr_accessible work in Rails?

I had a general question about Ruby on Rails and the attr_accessible attributes that go into models (Rails 3). Can someone explain what model attributes should be defined there? I remember something about the risk for mass use, although I do not know much about this aspect ... Thank you :)

+5
source share
4 answers

attr_accessible allows you to define a whitelist of attributes on a model that can be assigned to the mass. Therefore, if you have 10 attrs, but only 3 from the white list, only those three can be assigned as mass.

class Foo < ActiveRecord:Base
  #lets say you have attrs one, two, three
  attr_accessible :one, :two
end

#You can do this:
Foo.new({:one => 1, :two => 2})

#if you were to do this:
Foo.new({:one => 1, :two => 2, :three => 3})
#Foo three attr would not be set
+4
source

Imagine an order class with some fields:

Order.new({ :type => 'Corn', :quantity => 6 })

, , : price_off. : price_off attr_accessible. , - :

Order.new({ :type => 'Corn', :quantity => 6, :price_off => 30 })

: price_off, . POST .

attr_accessible , , .

attr_accessor attr_accessible .

+5

Rails ActiveRecord .

attr_accessible:

, -.

attr_protected:

, . URL- .

attr_accessible , , , , , , , , . , Rails Security Guide, Rails.

+1

attr_accessibleis a rail function with which we can enable the mass assignment of model attributes. It is just the opposite attr_protectedin functionality.

To make a particular attribute available for mass assignment, we use the attr_accessiblefollowing:

class Person < ActiveRecord::Base
attr_accessible : name
end



For a more detailed explanation attr_accessibleand Strong parametersyou can follow the link below:

[ http://findnerd.com/list/view/attr-accessible-in-Rails-4/3654/†[1]

0
source

All Articles