In Rails 3 I can perform query on associated models:
EXAMPLE 1:
model.associated_models.where(:attribute => 1)
associated_models is an array of models.
Is it possible to perform activerecord query on manualy created array of models?
EXAMPLE 2:
[Model.create!(attribute: 1), Model.create!(attribute: 2)].where(:attribute => 1)
Just like associated_models in first example its and array of models, but I guess there is something going on backstage when calling associated_models.
Can I simmulate this behaviour to get example 2 working?
short answer is no, you cannot. Activerecord scope chains construct queries for the db and this cannot be interpreted for arbitrary arrays, even if it is array of AR objects like in your example.
You can ‘simulate’ it by either a proper db scope
(but this is wrong, since you want to do db calls only if needed) or by using array search:
Also note that model.associated_models is not an Array, but a
ActiveRecord::Associations::HasManyAssociation, a kind of association proxy. It is quite tricky cause even its ‘class’ method is delegated to the array it is coerced to, this is why you were misled I guess.