Geocoder Gem:如何在两个不同的模型之间使用? [英] Geocoder Gem: How to use between two different models?
问题描述
我正在使用地理编码器和
I'm using the Geocoder and Will Paginate gems to sort my results based on the distance from a user's location and a kids' mom's address. My models are like this:
class User
has_many :kids
geocoded_by :address
end
class Kid
belongs_to :mom
belongs_to :dad
end
class Mom
has_many :kids
has_many :dads, through: :kids
geocoded_by :address
end
class Dad
has_many :kids
has_many :moms, through: :kids
end
现在,我正在尝试使用将使用Users.address
的正确范围并将其与Kids.moms.addresses
Now, I'm trying to use the correct scope that I will use the Users.address
and compare it to the Kids.moms.addresses
def show
@dad = Dad.find(params[:id])
@user_location = current_user.address
@kids = @dad.kids.near(@user_location, 100).paginate(page: params[:page], per_page: 25).order(created_at: :desc)
end
这给了我错误:
NoMethodError - undefined method `address' for nil:NilClass:
app/controllers/dads_controller.rb:14:in `show'
actionpack (4.0.2) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.0.2) lib/abstract_controller/base.rb:189:in `process_action'
actionpack (4.0.2) lib/action_controller/metal/rendering.rb:10:in `process_action'
.......
有什么建议吗?
更新
到目前为止,我已经完成了此操作:
So far I've done this now:
class ApplicationController
before_filter :set_user_location
private
def set_user_location
if signed_in?
@user_location = current_user.address
end
end
end
class DadsController
def show
@dad = Dad.find(params[:id])
@kids = @dad.kids.joins(:mom).merge(Mom.near(@user_location, 100)).order(name: :asc, created_at: :desc).paginate(page: params[:page], per_page: 25)
end
上面的代码获取了当前用户的地址(使用Devise),但现在我得到了错误:
The code above gets the current users address to work (using Devise) but now I get the error:
ActiveModel::MissingAttributeError
missing attribute: birthday
针对页面上的所有我的孩子"属性.
For all of my Kids attributes on the page.
<% @kids.each do |kid| %>
<%= kid.birthday %>
<%= kid.name %>
<% if kid.upkeep.present? %>
<%= kid.upkeep %>
<%= kid.upkeep_size %>
<% end %>
<%= kid.age %>
<%= kid.favorite_color %>
<% end %>
我认为这是因为它认为妈妈与孩子具有相同的属性.有什么想法吗?
I think this is because it thinks Mom has the same attributes as the kid. Any ideas?
推荐答案
这是使用Geocoder的方法:
This is how you can do it with Geocoder:
def show
@dad = Dad.find(params[:id])
near = Mom.near(@user_location, 100, :select => "kids.*")
@kids = @dad.kids.joins(:mom).merge(near).order(name: :asc, created_at: :desc).page(params[:page])
end
我需要添加:select
选项.
这篇关于Geocoder Gem:如何在两个不同的模型之间使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!