Search code examples
ruby-on-railsrubymodelgeokit

Rails: Get Posts of Users within 10km of a point


I'm using the rails 3 geokit gem that allows you to find users within a distance of a point, e.g.

User.within(10, origin: [51.123123, 0.1323123])

['10' is the distance in mi/km; 51 & 0 are latitude and longitude]

I'm now trying to get all posts by users who are within a certain distance of a point. something like:

Post.where(User.within(10, origin: [51.123123, 0.1323123]))

(my Post model belongs_to my User model, my User model has_many posts)

Reading around it seems like the solution lies in .where, or using :through & :source, or .joins, but I haven't been able to nail it down.

I'd be very grateful for any help!


Solution

  • Try this solution:

    class Post
      acts_as_mappable through: :user
    end
    
    Post.joins(:user).within(10, origin: [51.123123, 0.1323123])