[英]ruby geocoder gem with a polymorphic resource
I've a bunch or addresses which belong to various other resources via polymorphic association 我通过多态关联有一堆或地址属于各种其他资源
belongs_to :addressable, :polymorphic => true
and my resource, lets say its a Hotel 和我的资源,让我们说它是一家酒店
has_one :address, :as => :addressable
I can search my address data no problem, find every address in a 20 mile radius of my search string for example 我可以搜索我的地址数据没问题,例如找到我搜索字符串半径20英里范围内的每个地址
@addresses = Address.near(params[:search],20, :order => :distance).page params[:page]
I'm really struggling to join the resource ie the hotel info, I can link through to a details page, but I'd like to show the name of the hotel in my results for example. 我真的很难加入资源,即酒店信息,我可以链接到详细信息页面,但我想在结果中显示酒店的名称。
I thought using :include may have helped thus: 我认为使用:include可能有助于:
@addresses = Address.near(params[:search],20, :order => :distance, :include => :hotel).page params[:page]
.. but no luck ..但没有运气
Any advice greatly appreciated. 任何建议都非常感谢。
Stew 炖
OK I figured it out with a little help from a colleague 好的,我在同事的帮助下弄明白了
@addresses = Address.where(addressable_type: 'Hotel').near(params[:search],20, :order => :distance).includes(:addressable).page params[:page]
Hope it might help someone else! 希望它可以帮助别人!
In your Address model, I would define the relation with the Hotel model 在您的地址模型中,我将定义与酒店模型的关系
belongs_to :addressable, :polymorphic => true
belongs_to :hotel, -> { where(adresses: {addressable_type: 'Hotel'}) }, foreign_key: 'addressable_id'
Like well explained in this answer, Eager load polymorphic 就像在这个答案中解释得好, Eager加载多态
Then, like explained in the geocoder doc https://github.com/alexreisner/geocoder#known-issue I would find hotels by location doing the following: 然后,就像地理编码器文档https://github.com/alexreisner/geocoder#known-issue中所解释的那样,我会按位置查找酒店,执行以下操作:
Address.near(generic_address, radius, :select => "addresses.*, hotels.*").joins(:hotel)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.