gpt4 book ai didi

ruby-on-rails - 如何使 named_scope 与连接表一起正常工作?

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:14 25 4
gpt4 key购买 nike

这是我的情况。我有两个表:质押和质押交易。当用户做出 promise 时,他在 promise 表中只有一行。

稍后当需要履行 promise 时,每笔付款都会记录在我的 pledge_transactions 表中。

我需要能够查询到所有未结质押,即交易表中的金额之和小于质押金额。

这是我目前所拥有的:

named_scope :open,
:group => 'pledges.id',
:include => :transactions,
:select => 'pledge_transactions.*',
:conditions => 'pledge_transactions.id is not null or pledge_transactions.id is null',
:having => 'sum(pledge_transactions.amount) < pledges.amount or sum(pledge_transactions.amount) is null'

您可能会问自己,为什么我指定了那个多余且荒谬的条件选项。答案是,当我不强制 ActiveRecord 在条件中确认 pledge_transactions 表时,它完全省略了它,这意味着我的 having 子句变得毫无意义。

我认为我遇到了 ActiveRecord 的缺点。

最终我需要能够执行以下操作:

  • promise .open
  • Pledge.open.count
  • Pledge.open.find(:all, ...)
  • 等等

有人对这个问题有更优雅的答案吗?请不要建议在每次交易发生时增加认捐 amount_given 字段。这感觉像是一种创可贴方法,我更喜欢在 promise 创建后保持静态并计算差异。

如果我不在这里使用 Rails,我会创建一个 View 并完成它。

谢谢!

最佳答案

:transactions 关联是如何定义的?它是否规定了 :class_name = 'PledgeTransaction'(或者无论类是什么,如果它使用 set_table_name)?

您看过:joins 参数了吗?我想这可能是你要找的。当然 :conditions 看起来不对。

If I weren't using Rails here, I'd just create a view and be done with it

仅仅因为它是 Rails 并不意味着您不能使用 View 。好吧,根据它的构造方式,您可能无法更新它,但否则就去做吧。您也可以在迁移中创建和删除 View :

class CreateReallyUsefulView < ActiveRecord::Migration
def self.up
# this is Oracle, I don't know if CREATE OR REPLACE is widely-supported
sql = %{
CREATE OR REPLACE VIEW really_usefuls AS
SELECT
... blah blah SQL blah
}
execute sql
end

def self.down
execute 'drop view really_usefuls'
end
end

class ReallyUseful < ActiveRecord::Base
# all the usual stuff here, considering overriding the C, U and D parts
# of CRUD if it's supposed to be read-only and you're paranoid
end

我认为书籍/文档不会涉及到这么多,因为 View 的实现和支持在不同平台上差异很大。

关于ruby-on-rails - 如何使 named_scope 与连接表一起正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1470139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com