1

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?

Cu1ture
  • 1,273
  • 1
  • 14
  • 29
  • 1
    Remember that Rails4 uses strong parameters: http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html – Alessandro De Simone Aug 05 '14 at 19:21
  • I am currently working with a tutorial that uses rails 3.2 has the way attr_accessible is used changed in rails 4? – Cu1ture Aug 05 '14 at 19:25
  • 1
    Yes, no more attr_accessible but strong parameters, read this: http://easyactiverecord.com/blog/2014/04/01/rails4-strong-parameters-and-the-attr-accessible-macro/ – Alessandro De Simone Aug 05 '14 at 19:28
  • Thanks! So in Rails 4 will the create method in the add action work by default without having to specify attr_accessible in the model class? – Cu1ture Aug 05 '14 at 19:30

1 Answers1

1

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • so does that mean that I can access instance variables of attirbutes in Rails using the equivalent symbol without having to specify attr_accessor because Rails automatically creates attributes? – Cu1ture Aug 05 '14 at 19:17
  • 2
    Yes, if it is a property that corresponds to a column in the database you can access it directly off of your model using hash `todo1[:name]` or dot `todo1.name` or `todo1.read_attribute(:name)` – CWitty Aug 05 '14 at 19:27