现在我正在通过Dealings.all获取交易信息,并执行以下拒绝语句,但是有一种方法可以让我一口气查询它吗?我有一些ruby代码,例如pluck和max,我想知道是否可以在SQL代码中混合使用ruby代码。
dealings.reject {| n |
(n.item_rank ==:import && n.dealings.pluck(:status).max == Contract :: import)|| (n.item_rank ==:process && n.dealings.pluck(:status).max == Contract :: process)|| (n.item_rank ==:export && n.dealings.pluck(:status).max == Contract :: export) }
结束
答案 0 :(得分:0)
我相信使用子查询是可能的。这是原始的sql示例:
negotiations = Negotiation.from('(select negotiations.*, (select max(status) from deal_buildings where deal_buildings.deal_id = negotiations.id) max_status from negotiations) negotiations')
negotiations = negotiations.where(business_rank: [17, 19, 22])
negotiations = negotiations.where(main_member_id: 7)
negotiations = negotiations.where(
'((business_rank = ? and max_status = ?) or (business_rank = ? and max_status = ?) or (business_rank = ? and max_status = ?)) is false',
'application', Supplier::Building::STATUS_APPLY,
'agreement', Supplier::Building::STATUS_CONTRACT,
'settlement', Supplier::Building::STATUS_SETTLEMENT
)
还有query object:
class NegotiationsQuery
def all
Negotiation.from(negotiations_and_max_status_query)
end
private
def negotiations
@negotiations ||= Arel::Table.new(:negotiations)
end
def deal_buildings
@deal_buildings ||= Arel::Table.new(:deal_buildings)
end
def max_status_query
deal_buildings.project(deal_buildings[:status].maximum).where(
deal_buildings[:deal_id].eq(negotiations[:id])
).as('max_status')
end
def negotiations_and_max_status_query
negotiations.project(negotiations[Arel.star], max_status_query).as('negotiations')
end
end
negotiations = NegotiationsQuery.new.all
negotiations = negotiations.where(business_rank: [17, 19, 22])
negotiations = negotiations.where(main_member_id: 7)
negotiations = negotiations.where(
'((business_rank = ? and max_status = ?) or (business_rank = ? and max_status = ?) or (business_rank = ? and max_status = ?)) is false',
'application', Supplier::Building::STATUS_APPLY,
'agreement', Supplier::Building::STATUS_CONTRACT,
'settlement', Supplier::Building::STATUS_SETTLEMENT
)