簡體   English   中英

將IN上的SQL轉換為Active Record查詢匹配

[英]Convert SQL to Active Record Query matching on IN

我如何將這種SQL轉換為Active Record語法。 我一直在努力解決其他方面的問題。

SELECT \\"accounts\\".* FROM account_categories, accounts WHERE \\"accounts\\".\\"worksheet_id\\" = 5 AND (account_categories.name IN ('Savings','Deposit') AND account_categories.id = accounts.account_category_id) ORDER BY \\"accounts\\".\\"id\\" ASC"

worksheet_id會有所不同,並不總是5。

我想在客戶模型的范圍內使用它。 像這樣

scope :savings, -> { from('account_categories, accounts').where("account_categories.name = ? AND account_categories.id = zen_accounts.account_category_id", 'Savings') }

但是測試儲蓄和存款是這樣的:

scope :savings_and_deposit, -> { from('account_categories, accounts').where("account_categories.name = ? AND account_categories.id = zen_accounts.account_category_id", ['Savings','Deposit]) }

試試這個代碼:

scope :savings, -> (worksheet_id) { filtered_categories(worksheet_id, ['Savings']) }
scope :savings_and_deposit, -> (worksheet_id) { filtered_categories(worksheet_id, ['Savings', 'Deposit']) }

scope :filtered_categories, -> (worksheet_id, category_names) do 
  joins(:account_categories).
  where(worksheet_id: worksheet_id).
  where(account_categories: {name: category_names}).
  order(id: :asc)
end

此代碼假定哪種Account模型已經具有關系account_categories ,否則將joins(:account_categories)替換為joins("JOIN account_categories ON account_categories.id = accounts.account_category_id")

暫無
暫無

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

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