Reputation: 15002
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'
Upvotes: 3
Views: 2024
Reputation: 1184
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
Upvotes: 0
Reputation: 3459
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
.
Upvotes: 5