Ruby on rails 查询和即时加载关联
我有两个模型,需要查询以下字段Ruby on rails 查询和即时加载关联,ruby-on-rails,ruby,ruby-on-rails-4,arel,Ruby On Rails,Ruby,Ruby On Rails 4,Arel,我有两个模型,需要查询以下字段 客户 :名字 :姓氏 :地址 :电子邮件 亲属 :名字 :姓氏 :地址 :标题 客户有许多亲戚 我正在尝试编写一个search()方法,该方法将返回Customer记录的集合,其中Customer的字段或与其相关的1+个亲戚匹配查询 目标是能够迭代客户记录的集合。如果customer.relatives.present?,我将知道通过customer提供的相关Relative模型循环,该集合中的模型与查询匹配 我现在有这样的东西: class Cust
客户
:名字
:姓氏
:地址
:电子邮件
亲属
:名字
:姓氏
:地址
:标题
客户
有许多亲戚
我正在尝试编写一个search()
方法,该方法将返回Customer
记录的集合,其中Customer
的字段或与其相关的1+个亲戚
匹配查询
目标是能够迭代客户
记录的集合。如果customer.relatives.present?
,我将知道通过customer
提供的相关Relative
模型循环,该集合中的模型与查询匹配
我现在有这样的东西:
class Customer < ActiveRecord::Base
has_many :relatives
def self.search(params={})
cols = %i(address caseworker last_name)
conds = []
cols.reject! { |col| params[col].blank? }
conds << cols.collect { |col| "clients.#{col} like ?" }.join(" or ")
cols.each { |col| conds << "%#{params[col]}%" }
query = self.send(:where, conds)
# @todo query relatives here!
end
end
class客户 conds根据您的数据库,您可能希望查看类似全文搜索的内容
在建立搜索索引之后,与客户查询匹配的快速加载关系就变得很简单了
class Customer < ActiveRecord::Base
include PgSearch
has_many :relatives
pg_search_scope :search,
:against => [:address, :caseworker, :last_name]
:associated_against => {
:relatives => [:address, :caseworker, :last_name]
}
end
Customer.search("foobar").preload(:relatives)
class客户[:地址,:个案工作者,:姓氏]
:关联_反对=>{
:亲属=>[:地址,:个案工作者,:姓氏]
}
结束
Customer.search(“foobar”).preload(:亲戚)
此gem是mysql数据库搜索和全文搜索的简单实现
您可能需要进行一些编码,以使gem正常工作,例如定义搜索文本等。但此gem将处理其余部分。这非常有趣。你知道MySQL的等价物吗?另外,preload(:relatives)
将加载所有亲属,而我只对那些特别导致客户
被包含在原始集合中的亲属感兴趣。我没有在MySQL中进行全文搜索的任何经验,但是想到Sphinx()看起来很有希望,很抱歉,我错过了只加载匹配查询的亲属的要求。我会考虑一下的。。