3

I have a user model => @user

I want to add new attribute current_time to @user for temporary use.

Don't want to do migration to add a column (just for temporary use):

@user.current_time = Time.now

Is there any way to achieve this?

NoMethodError (undefined method `current_time=' for #<User:0x007fd6991e1050>):
  app/controllers/carts_controller.rb:47:in `block in search_user'
  app/controllers/carts_controller.rb:45:in `search_user'
phoet
  • 18,688
  • 4
  • 46
  • 74
newBike
  • 14,385
  • 29
  • 109
  • 192

2 Answers2

5

attr_accessor will set up a reader and writer for the instance variable:

class Foo
  attr_accessor :current_time
end

foo = Foo.new
foo.current_time = Time.now   # Writes value
foo.current_time              # Reads value

You might also be interested in attr_reader and attr_writer.

phoet
  • 18,688
  • 4
  • 46
  • 74
kristinalim
  • 3,459
  • 18
  • 27
0

Try to define few methods in User.model:

def current_time= (time)
  @current_time = time
end

def current_time
  @current_time
end

UPD according to precisely right comment from kristinalim

Note, that attr_accessible, being part of framework, was deprecated in Rails 4. Now strong params are used instead. At the same time getter/setter attr_accessor is part of core Ruby and works as usual.

The difference between attr_accessible and attr_accessor is in very well explained in this post

Community
  • 1
  • 1
Leger
  • 1,184
  • 8
  • 7
  • Do you mean that `attr_accessible` is deprecated? AFAIK, `attr_accessor` is part of Ruby core and is still alive. – kristinalim Oct 25 '13 at 09:35