Kevin
Kevin

Reputation: 1614

Rails query portion of model

How would i do a query like this. i have

@model = Model.near([latitude, longitude], 6.8)

Now i want to filter another model, which is associated with the one above. (help me with getting the right way to do this)

model2 = Model2.where("model_id == :one_of_the_models_filtered_above", {:one_of_the_models_filtered_above => only_from_the_models_filtered_above})

the model.rb would be like this

has_many :model2s

the model2.rb

belongs_to :model

Im on rails 3

Right now it is like this (after @model = Model.near([latitude, longitude], 6.8)

model2s =[]
models.each do |model|
   model.model2s.each do |model2|
      model2.push(model2)
   end
end

I want to accomplish the same thing, but with an active record query instead

I partially found an answer to my question. It still incorporates my old method which i am unhappy about.

models.each do |model|
   models-model2s = Model2.where("model_id => :modid",{:modid => model.id})
   model2 += model
end

But this is a kind of a dumb approach, fooling around with tadman's approach showed me that model.model2s is a command i can execute (which i forgot), so

models.each do |model|
   model2s += model.model2s
end

This isn't completely what i was looking for, but im using it until i see something better. (Im still thinking of tadman's reverse approach)

i think i found something, why does this fail

Model2.where("model.distance_from([:latitude,:longitude]) < :dist", {:latitude => latitude, :longitude => longitude, :dist => 6.8})

this query throws this error

SQLite3::SQLException: near "(": syntax error: SELECT "tags".* FROM "tags"  WHERE (model.distance_from([43.45101666666667,-80.49773333333333]) < 6.8)

, why

Upvotes: 1

Views: 140

Answers (1)

tadman
tadman

Reputation: 211590

You might have some luck with just retrieving the second type of model indirectly:

@models = Model.near([ latitude, longitude ], 6.8).includes(:model2s)

That will pre-load all the "model2s".

Or you can try flipping it around and retrieving the Model2s directly, but you'd have to be able to express the near condition some other way:

@model2s = Model2.includes(:model).where('models.x' => ...)

Upvotes: 1

Related Questions