Reputation: 4510
I have an ActiveRecord
object that I want to manipulate without saving to the database. When I try to manipulate it using setters, it turns into an array and I can't call anymore ActiveRecord methods
on it anymore. Is there a way to prevent against this.
Here is my situation:
I have a model Server
, and I want to create a method that returns all Server
records, sets a attribute
called imported
to false
, then returns the ActiveRecord
list of all Servers
with their newly updated imported
attribute, all without changing the database.
Here is what I have
def servers_imported
servers = Servers.all
servers.each do |server|
server.imported = false
end
servers
end
My solution effectively changes the imported
attributes of all the Servers
without actually saving this change to the database. However, the return value servers
is an array
and not an ActiveRecord
object. I need it to be an ActiveRecord
object because I need to use additional methods.
Upvotes: 0
Views: 1429
Reputation: 812
When you call servers = Server.all
you get an array of active record objects. You iterate this collection and return this array. The servers
variable is a collection all the time. If you need to use additional methods on active record objects you need iterate it again.
def servers_imported
servers = Servers.all
servers.each do |server|
server.imported = false
end
servers
end
my_servers = servers_imported
my_servers.each do |server|
server.my_pretty_method
end
Upvotes: 1