1

I have a User model.

And User has a field called Balance (which represents how much money he has in his account).

I clearly don't want to make it attr_accessible.

But I want to be able to change its value (say when I charge him for something).

How do I write a getter/setter method for this attribute?

user1885058
  • 589
  • 2
  • 8
  • 17

2 Answers2

0

@object.attribute = new_value attr_accesible is a protection from mass assignment don't mess it with attr_accessor which creates getters and setters

Here is question about difference Difference between attr_accessor and attr_accessible

Community
  • 1
  • 1
Tolik Kukul
  • 1,996
  • 16
  • 26
0

attr_accessible protects you from mass assignment, as used by update_attributes and similar.

It doesn't affect reading the value of that attribute at all, and it doesn't affect you calling the accessor directly. For example you could write

user.balance -= item.price
user.save!

Presuming that you have previously verified that this is indeed the correct action to take.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174