簡體   English   中英

雙重加入 rails 查詢

[英]Double Join in rails query

我有這三個表如下

辦公室.rb

has_many :documents
has_one :information

信息.rb

belongs_to :office

文檔.rb

belongs_to :office

我正在嘗試編寫一個查詢,如下所示

文檔_控制器.rb

def search
 @documents = Document.all
 @documents.joins(:office).where("offices.name ILIKE ?", "%#{params[:search]}%") OR @documents.joins(:office).joins(:information).where("informations.first_name ILIKE ? OR informations.last_name ILIKE ?", "%#{params[:search]}%", "%#{params[:search]}%")
end

我正在努力實現上述聲明,但我做錯了什么。 請幫我解決這個問題

因此,我們的想法是檢索辦公室名稱是搜索詞或信息名字/姓氏是搜索詞的任何文檔,對嗎?

第一步是創建連接:

Document.joins(office: :information)

第二步是創造條件:

where("offices.name ILIKE :term OR informations.first_name ILIKE :term OR informations.last_name ILIKE :term", term: "%#{params[:search]}%")

並加入兩個句子:

Document.joins(office: :information).where("offices.name ILIKE :term OR informations.first_name ILIKE :term OR informations.last_name ILIKE :term", term: "%#{params[:search]}%")

還有其他奇特的方法可以做同樣的事情,比如使用or scope,但理解起來可能會更復雜:

search_term = "%#{params[:search]}%"
base_query = Document.joins(office: :information)
office_scope = base_query.where("offices.name ILIKE :term", search_term)
first_name_scope = base_query.where("informations.first_name ILIKE :term", search_term)
last_name_scope = base_query.where("informations.last_name ILIKE :term", search_term)
office_scope.or(first_name_scope).or(last_name_scope)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM