If I want to do this but not save to the database, how can I go about
it?
things.each do |thing|
changed = someotherqueryresult
thing.update_attribute :testattrib, changed
end
Essentially I want to create a collection called things with some extra
attributes that are not saved into the database, as they are just used
for sorting in a view and should not be saved (in fact saving them
wastes time each time I refresh the view).
If I want to do this but not save to the database, how can I go about
it?
things.each do |thing|
changed = someotherqueryresult
thing.update_attribute :testattrib, changed
end
Essentially I want to create a collection called things with some extra
attributes that are not saved into the database, as they are just used
for sorting in a view and should not be saved (in fact saving them
wastes time each time I refresh the view).
Can anyone help?
Thanks,
Chris
put this at the top of your model
class Foo < ActiveRecord::Base
attr_accessor :bar
end
which is the same as:
class Foo < ActiveRecord::Base @bar = nil
def bar @bar
end
def bar=(value) @bar = value
end
end
This creates getters and setters for an instance variable that doesn’t
know about the database.
foo = Foo.new
foo.bar = ‘baz’
foo.bar #=> ‘baz’
Although this will not work with the update_attrubute methods because
those are defined by active record and work only on database fields.
Also note that since the value is not stored inthe database, it will be
cleared after every request unless it’s in somewhere like the session,
which stays around between requests.
It doesn’t make any difference, but it appears as though you are
confusing two types of instance variables (since the three @bar
variables do not reference the same variable). The @bar variables
inside the functions are local to objects of the class, the @bar
variable outside the function is local to the class itself. For
example:
class Foo < ActiveRecord::Base @bar = 42 # class instance variable
def self.bar # class method @bar # class instance variable
end
def bar # instance method @bar # instance variable
end
def bar=(value) # instance method @bar = value # instance variable
end
end
Although this will not work with the update_attrubute methods because
those are defined by active record and work only on database fields.
I think what you’re saying in the statement above is that
update_attributes(:bar => ‘hello’) will not work.
That’s not the case. Under the hood you’ll find that new({}),
attributes = {}, update_attribute(x,y) and update_attributes({}) all delegate the assignment to your methods.
So, in your example, update_attributes(:bar => ‘hello’) will call
bar=‘hello’.