Eric Francis
Eric Francis

Reputation: 24267

Does attr_accessible create getters and setters?

Does attr_accessible create getters and setters?

I keep reading that attr_accessible and attr_accessor are different. But in my code base I keep seeing people write:

attr_accessor :email
attr_accessible :email

And this seems odd. Does attr_accessible not create getters and setters?

For rails 4, I know to use strong parameters, so is it best to only use attr_accessor?

Edit: I've seen this posted on SO many times:

attr_accessor makes getters and setters while attr_accessible allows to pass values in a mass assignment.

I'm more looking for a 'Yes' or 'No' to my question. If the answer is No, does rails automatically create getters and setters for columns in your database?

Edit: so I think I get it now.

attr_accessor :email
attr_accessible :email

Doing the above, would allow you to mass-assign a virtual property that would not be saved to the database. Correct?

Upvotes: 1

Views: 235

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84114

attr_accessible does not create accessors.

Activerecord generates accessors for database columns automatically. attr_accessible and attr_protected just control whether they will be invoked from methods such as update_attributes (And can be use with any accessor methods, not just ones backed by database columns)

Upvotes: 2

acacia
acacia

Reputation: 1387

YES attr_accessible create getters and setters.

attr_accessible is normally used for models with corresponding tables while attr_accessor for models with no corresponding database tables.

Upvotes: 0

Related Questions