【发布时间】:2019-09-14 07:55:35
【问题描述】:
如何在 Ruby on Rails 上查询或在 Ruby on Rails 上翻译此查询?
SELECT
orders.item_total,
orders.total,
payments.created_at,
payments.updated_at
FROM
public.payments,
public.orders,
public.line_items,
public.variants
WHERE
payments.order_id = orders.id AND
orders.id = line_items.order_id AND
这适用于 Postgres,但我是 RoR 的新手,这让我难以查询此示例。
到目前为止,这就是我所拥有的。
Order.joins(:payments,:line_items,:variants).where(payments:{order_id: [Order.ids]}, orders:{id:LineItem.orders_id}).distinct.pluck(:email, :id, "payments.created_at", "payments.updated_at")
在提问之前我有很多参考资料,这里是链接。
How to combine two conditions in a where clause?
Rails PG::UndefinedTable: ERROR: missing FROM-clause entry for table
Rails ActiveRecord: Pluck from multiple tables with same column name
ActiveRecord find and only return selected columns
https://guides.rubyonrails.org/v5.2/active_record_querying.html
从所有链接中,我生成了这段可用于测试的代码。
Spree::Order.joins(:payments,:line_items,:variants).where(id: [Spree::Payment.ids]).distinct.pluck(:email, :id)
但是当我尝试进行多个查询并从不同的表中提取特定的列名时,它会给我一个错误。
更新
所以我使用 Ransack 来查询我生成了这段代码。
@search = Spree::Order.ransack(
orders_gt: params[:q][:created_at_gt],
orders_lt: params[:q][:created_at_lt],
payments_order_id_in: [Spree::Order.ids],
payments_state_eq: 'completed',
orders_id_in: [Spree::LineItem.all.pluck(:order_id)],
variants_id_in: [Spree::LineItem.ids]
)
@payment_report = @search.result
.includes(:payments, :line_items, :variants)
.joins(:line_items, :payments, :variants).select('payments.response_code, orders.number, payments.number')
删除选择部分时没有错误,我需要获取该特定列。有什么办法吗?
【问题讨论】:
-
给你什么错误?
-
这里出了点问题`orders:{id:LineItem.orders_id})`order_ids 可能吗?
-
我收到一个错误,缺少 FROM-Clause...
-
您必须在表格中使用
spree_后缀。spree_payments、spree_orders等 -
@GonzaloMorenoCaballero 是的,我刚刚想通了。但其他数据仍然缺失,例如
spree_payments.response_code和其他 2 个。
标签: ruby-on-rails rails-activerecord