2017-05-07 35 views
0

如何将这种SQL转换为活动记录语法。 我一直在努力解决主要与其他元素的IN。将SQL转换为在IN上的活动记录查询匹配

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

我想在Account模型中的范围使用此。 这样

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]) }

+0

您最后一个查询两个名称的示例不起作用?你得到哪个错误?你在这里错过了'['Savings','Deposit]'结束报价。 –

+0

@Evolve:你为什么不在(?)'中使用'account_categories.name? –

回答

1

试试这个代码:

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模型已经有relati account_categories,否则请用joins("JOIN account_categories ON account_categories.id = accounts.account_category_id")替换joins(:account_categories)