lundi 21 septembre 2015

Missing Attribute after applying joins and merge on Rails

I have two models;

Category

has_many :locations

Location

belongs_to :category
reverse_geocoded_by :latitude, :longitude do |obj,results|
 if geo = results.first
    obj.address = geo.address
    obj.city    = geo.city
    obj.country = geo.country_code
 end
end
after_validation :reverse_geocode

when I apply, to get the nearest category for that location. I used near scope in geocoder gem here.

Category.joins(:locations).merge(Location.near("Tignale"))

In SQL

    SELECT locations.*, (69.09332411348201 * ABS(locations.latitude - 45.7426301) * 0.7071067811865475) + (59.836573914187355 * ABS(locations.longitude - 10.7091062) * 0.7071067811865475) AS distance, CASE WHEN (locations.latitude >= 45.7426301 AND locations.longitude >= 10.7091062) THEN  45.0 WHEN (locations.latitude <  45.7426301 AND locations.longitude >= 10.7091062) THEN 135.0 WHEN (locations.latitude <  45.7426301 AND locations.longitude <  10.7091062) THEN 225.0 WHEN (locations.latitude >= 45.7426301 AND locations.longitude <  10.7091062) THEN 315.0 END AS bearing FROM "categories" INNER JOIN "locations" ON "locations"."category_id" =
 "categories"."id" WHERE (locations.latitude BETWEEN 45.4531665337783 AND 46.0320936662217 AND locations.longitude BETWEEN 10.29433218237017 AND 11.123880217629832)  ORDER BY distance ASC

I get just this.

[#<Category:0xb090be0
  id: 3,
  created_at: Thu, 03 Sep 2015 21:46:12 UTC +00:00,
  updated_at: Sat, 05 Sep 2015 21:36:19 UTC +00:00>]

Some other attributes on category models are missing for example 'name' etc.

Aucun commentaire:

Enregistrer un commentaire