I am new to learning Rails but my current understanding of attr_accessible
is that it makes an attribute of a class available outside the class scope.
However without making an attribute attr_accessible
I am able to access that attribute in a helper method argument in the Rails console.
'005 > Todo.create(:todo_item => "Pay internet bill")
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "todos" ("created_at", "todo_item", "updated_at") VALUES (?, ?, ?) [["created_at", Sat, 18 Aug 2012 09:55:33 UTC +00:00], ["todo_item", "Pay internet bill"], ["updated_at", Sat, 18 Aug 2012 09:55:33 UTC +00:00]]
(339.1ms) commit transaction
=> #<Todo id: 6, todo_item: "Pay internet bill", created_at: "2012-08-18 09:55
However to do the same thing in a controller action :
def add
Todo.create(:todo_item => params[:todo_text])
redirect_to :action => 'index'
end
In the model I need to specify
attr_accessible :todo_item
Why is this attribute accessible in the Rails console but not in a controller method?
ActiveRecord creates attributes automatically based on the database schema. This is a system superficially similar to but independent from the attr_accessor
system that's part of core Ruby.
Internally they have nothing in common. An attr_accessor
is just a wrapper around a simple instance variable but inside a model instance there's a lot more going on.
You can add accessible attributes to your models for things that need to be stored temporarily but not in the database. This is a fairly uncommon thing to do, though.