Martin
Martin

Reputation: 11336

Inverse association in Rails ActiveRecord

I have two ActiveRecord models. Idea and User. There's an association between the two that is working like User.idea.

The User model currently save lat and lng coordinates from the user.

From ideas controller, I would like to query all ideas that match a certain location. I'm not how can I do this inverse join query in Rails.

Upvotes: 1

Views: 1044

Answers (3)

jdoe
jdoe

Reputation: 15771

I guess you want this:

Idea.joins(:user).where(user: {lat: some_lat, lng: some_lng}).all

some_lat/some_lng can be a Range. Rails will handle the magic.

Upvotes: 1

klump
klump

Reputation: 3269

I guess you have to search for all the users which match your location and include the ideas while loading.

# first about the near by:
def close_to( position )
  (position-0.2)..(position+0.2)
end

@users = User.where( :lat => close_to(some_lat), :lng => close_to(some_lng) ).includes( :ideas )

# if you need all the ideas:
@ideas = []
@users.each do |user|
  @ideas += user.ideas
end

Otherwise you have in the users array all the ideas sorted by the user. Or did I miss your question?

Upvotes: 0

First: How do you find the wanted locations? Probably you could use something like Geocoder (there is a RailsCast about it).

Now I'll have a similar problem in the near future but for the moment I thought I'll probably do it in two steps (double query):

@users = User.near(params[:location]).pluck(:id)
@ideas = Ideas.where(:user_id => @users)

This way you get the ideas near the wanted location (I've used the Geocoder method here but you could get the users in a different way).

Note: I'm assuming a user has many ideas and an Idea belongs to a user

Upvotes: 1

Related Questions