如何使用Geocoder创建模型范围?

时间:2014-05-08 10:59:43

标签: ruby-on-rails ruby ruby-on-rails-4

我有以下型号,用户,爸爸,妈妈,跟随和孩子。

class User
 has_many :kids
 has_many :follows
 geocoded_by :address
end

class Dad
 has_many :kids
 has_many :follows
end

class Mom
 has_many :kids
 geocoded_by :address
end

class Follow
 belongs_to :dad
end

class Kid
 belongs_to :mom
 belongs_to :dad
 belongs_to :user
end

使用Geocoder宝石,我正在尝试创建一个范围,该范围记录了最接近用户位置的爸爸孩子的总数,与今天发生的儿童妈妈的位置相比。

<% @follows.each do |f| %>
 <% f.dad.kids.today.nearest.count
<% end %>

在我的 ApplicationController

def set_user_location
  if signed_in?
   @user_location = current_user.address
  end
end

在我的Kid模型中:

scope :today, -> { where("kids.created_at > ?", Time.now.beginning_of_day) }
scope :nearest, -> { joins(:mom).merge(Mom.near(@user_location, 2000)) }

nearest不起作用。它根本不会加载Moms

User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 5 ORDER BY "users"."id" ASC LIMIT 1
Processing by FollowsController#index as HTML
  Follow Exists (0.3ms)  SELECT 1 AS one FROM "follows" WHERE "follows"."user_id" = $1 LIMIT 1  [["user_id", 5]]
  Follow Load (0.5ms)  SELECT "follows".* FROM "follows" INNER JOIN "dads" ON "dads"."id" = "follows"."dad_id" WHERE "follows"."user_id" = $1 ORDER BY name ASC LIMIT 30 OFFSET 0  [["user_id", 5]]
  Product Load (0.2ms)  SELECT "dads".* FROM "dads" WHERE "dads"."id" = $1 ORDER BY "dads"."id" ASC LIMIT 1  [["id", 39]]
   (0.7ms)  SELECT COUNT(*) FROM "kids" WHERE "kids"."dad_id" = $1 AND (kids.created_at > '2014-05-08 04:00:00.000000')  [["dad_id", 39]]
  CACHE (0.0ms)  SELECT COUNT(*) FROM "kids" WHERE "kids"."dad_id" = $1 AND (kids.created_at > '2014-05-08 04:00:00.000000')  [["dad_id", 39]]

编写nearest范围的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

问题在于today范围,而非nearest。 每个模型都有sreated_at字段,所以在你的范围内你应该写

scope :today, -> { where("kids.created_at > ?", Time.now.beginning_of_day) }

编辑: 另一个错误是您在模型中引用控制器实例变量。模型和控制器是分开的,所以它不会这样工作。相反,你应该将范围重写为

scope :nearest, ->(location, distance=2000) { joins(:mom).merge(Mom.near(location, distance)) }

然后在控制器中你可以写

Kid.nearest(some location goes here)

但是我认为你的模型有点搞砸了,你希望他们做些不同的事情。 我想你要做的就是找一个离孩子最近的母亲,所以你应该做一些像

这样的事情
Mom.near(some_kid, 2000)