【发布时间】:2015-01-08 03:52:04
【问题描述】:
我有两个 ActiveRecord 关系,分别称为 rel1 和 rel2。它们每个都添加了各种不同的joins 和where 子句。
我想对它们中的每一个应用一个特定的相同序列的子句,我不想重复自己。
一种方法是创建一个函数:
def without_orders rel
rel.joins("LEFT JOIN orders ON customers.id = orders.customer_id").where("customers.id IS NULL")
end
rel1 = Customer
rel2 = Customer
# add a bunch of clauses to rel1
# add some other clauses to rel2
rel1 = without_orders(rel1)
rel2 = without_orders(rel2)
理想情况下,我不会将 without_orders 作为单独的函数。我会以某种方式将joins 和where 放在func 的本地,然后将其应用于rel1 和rel2。
这可能吗?如果不是,这里的正确方法是什么?
【问题讨论】:
标签: sql ruby-on-rails activerecord arel