Ronan Lopes
Ronan Lopes

Reputation: 3398

Rails - Temporary ActiveRecord Relation

I wanna create a method for return of my all objects for some model. The thing is, further than the persisted objects on db, I wanna join some more objects based on some condition. So it would be something like

MyModel.all + [some_array].map{|a| MyModel.new(attribute: a)}

The thing is: those new records wouldn't be persisted on the db. They would be created on the fly as new records to join the persisted ones. That way I showed kinda works, I get a array of objects of MyModel, but the problem is, since it's not an ActiveRecord relationship, I can't do a where on that set of records.

Any ideas for a workaround?

Upvotes: 0

Views: 289

Answers (1)

Doon
Doon

Reputation: 20232

what do you mean a where on that set of records? At the end of that code you should have an array of MyModel objects, some persisted, some not. If you need to then get a further subset of those objects, you can probably use any Enumerable method, such as select

 myarray = MyModel.all + [some_array].map{|a| MyModel.new(attribute: a)}
 #as opposed to myarray.where(attribute: 'key')
 myarray.select {|obj| obj.attribute == 'key' } 

Upvotes: 1

Related Questions