[英]Convert SQL to Active Record Query matching on IN
How would I convert this sort of SQL into Active Record Syntax. 我如何将这种SQL转换为Active Record语法。 I've struggled mainly resolving the IN with the other elements. 我一直在努力解决其他方面的问题。
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 will vary, won't always be 5. worksheet_id会有所不同,并不总是5。
I want to use this in a scope in the Account model. 我想在客户模型的范围内使用它。 Similar like this 像这样
scope :savings, -> { from('account_categories, accounts').where("account_categories.name = ? AND account_categories.id = zen_accounts.account_category_id", 'Savings') }
but testing for both Savings & Deposit something like this: 但是测试储蓄和存款是这样的:
scope :savings_and_deposit, -> { from('account_categories, accounts').where("account_categories.name = ? AND account_categories.id = zen_accounts.account_category_id", ['Savings','Deposit]) }
Try this code: 试试这个代码:
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
This code supposes what Account
model already has relation account_categories
, otherwise replace joins(:account_categories)
with joins("JOIN account_categories ON account_categories.id = accounts.account_category_id")
此代码假定哪种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.