gpt4 book ai didi

ruby-on-rails - Rails 3 多模型查询

转载 作者:行者123 更新时间:2023-12-04 03:41:18 25 4
gpt4 key购买 nike

我有以下模型:

class Location < ActiveRecord::Base
has_many :location_items
has_many :items, :through=>:location_items
end

class Item < ActiveRecord::Base
has_many :location_items
has_many :locations, :through=>:location_items
end

class LocationItem < ActiveRecord::Base
belongs_to :item
belongs_to :location
end

我还为项目模型启用了全文搜索(来自 gem),我可以做到
Item.search('keyword') -- 'search' 是 gem 提供的范围,用于获取名称或描述匹配关键字的所有项目,结果项目添加了一个 'rank' 属性用于匹配的相关性

我还为位置模型启用了地理搜索(来自 gem),我可以
Location.near('Toronto.ON', 100) --- 'near' 是 gem 提供的范围,用于获取距离多伦多 100 公里内的所有位置,结果位置添加了一个距离给定距离的 'distance' 属性位置 - 本例中为多伦多

所以现在我要做的是获取 location_item 对象的列表,这些对象的位置与特定给定位置匹配,并且项目与给定关键字匹配。
例如,在距离多伦多 100 公里内搜索与“关键字”匹配的 location_item 对象。

如何通过 实现此目的?一个 询问?并且还可以通过 location_item 对象中的关联项目和位置访问距离和排名属性。

我似乎无法链接范围,因为它们仅适用于项目和位置,而不是 LocationItem,

例如,下面的表达式将不起作用

LocationItem.joins(:items, locations).search('keyword').near('Toronto, ON', 100)

希望我对我正在尝试做的事情的描述是有意义的。你有什么主意吗?非常感谢你!

最佳答案

基本上,您将无法在一个查询中完成您想做的所有事情并保留您正在寻找的正常 LocationItem#location 和 LocationItem#item 界面。我将假设您使用的是 Postgres 的全文搜索,因为如果您使用的是 Solr 或 Sphinx**,这个问题就没有意义*。

如果你想要一个查询,但不介意放弃返回元素的 belongs_to 接口(interface):ActiveRecord::Base 自动从查询的 SELECT 部分(如果提供)分配属性,如下所示:Location.select('id+1 as more_id').first.more_id #=> 2因此您可以利用它来发挥自己的优势,并创建具有位置和项目以及 item_rank 和 location_dist 的适当部分的属性。

class LocationItem < ActiveRecord::Base

#This presumes that your geo and search gems actually return scopes that
# properly respond to to_sql (which they should if you're using rails 3).
def self.local_matching_items(text, dist=100)
LocationItem
.joins("INNER JOIN #{Item.search(text).to_sql} as matching_items
on matching_items.id
= location_items.item_id")
.joins("INNER JOIN #{Location.near(dist).to_sql} as nearby_locations
on nearby_locations.id
= location_items.location_id")
.select("location_items.id, nearby_locations.distance, matching_items.rank,
nearby_locations.other_field_you_might_want as
location_other_field_you_might_want,
matching_items.name as item_name, etc")
#returns LocationItems with #id, #distance, #rank,
# location_other_field_you_might_want, #item_name, etc
#It might be most helpful to distinguish between these
# and normal location_item's by storing them in variables with a
# different naming convention like nearby_item_matches.
end
end

*因为那时您将执行两个查询,一个用于通过您的搜索提供程序匹配关键字,一个用于从数据库中获取您的记录。

** 如果您使用 ThinkingSphinx,则支持 searching by geographical distance已经,但是您必须以不同的方式定义索引并以不同的方式调用 LocationItem#search。

关于ruby-on-rails - Rails 3 多模型查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6178654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com