Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does attr_accessible work in Rails?

I just had a general question about Ruby on Rails and the attr_accessible attributes that go in the models (Rails 3). Can someone explain which model attributes are supposed to be defined there? I remember something about risk for mass assignment, though I'm not too knowledgeable in this aspect... Thanks :)

like image 866
trflach Avatar asked Aug 24 '11 18:08

trflach


2 Answers

Imagine an order class with some fields:

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

Now imagine that the order also has a discount code, say :price_off. You wouldn't want to tag :price_off as attr_accessible. This stops malicious code from being able to craft a post that ends up doing something like so:

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

Even if your form doesn't have a field for :price_off, if it's just in your model by default it's available. A crafted POST could still set it.

Using attr_accessible white lists those things are can be mass assigned and protects fields that you want explicit control of in your code.

Difference between attr_accessor and attr_accessible has some additional links.

like image 183
Paul Rubel Avatar answered Sep 26 '22 20:09

Paul Rubel


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

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's three attr would not be set
like image 23
Jake Dempsey Avatar answered Sep 24 '22 20:09

Jake Dempsey