1

Ruby で Sinatra と DataMapper を使用して、単純な予算アプリに取り組んでいます。

過去 30 日間のすべての収入勘定にわたるすべてのトランザクションの合計を取得したいと考えています。

のようなものAccount.income_accounts.account_entries.sum(:amount, :transaction_date.gte => Date.today - 30)が動作するはずです。代わりに、制限条件 ontransaction_dateは無視され、すべての収入勘定のすべてのエントリの金額の合計が返されます。

以下を考えると:

class Account
  include DataMapper::Resource

  has n, :account_entries

  property :id,        Serial
  property :name,      String
  property :acct_type, String

  def self.income_accounts
    all(:acct_type => 'Income')
  end
end

class AccountEntry
  include DataMapper::Resource

  belongs_to :account

  property :id,               Serial
  property :account_id,       Integer
  property :description,      String
  property :amount,           BigDecimal
  property :transaction_date, DateTime
end

私はきちんと要求してdm-aggregatesいます。DataMapper は初めてです。問題があれば、sqlite3 データベースを使用しています。ルビーを使用して結果を合計することに頼りたくありません。また、このタイプの単純な集計クエリに対して生の SQL を実行することに頼るのは、間違っていると感じています。

誰でもこれに光を当てることができますか?DataMapper のチェーン ファインダー、特に集計に関して、正しい方向性を示していただければ幸いです。API と DataMapper サイトを調べてみましたが、まだ解決策はありません。

4

4 に答える 4

2

例をテストするための小さなスタンドアロンスクリプトを作成しましたが、正しい結果が返されるようです。私はedgeextlib、dm-core、dmを使用していることに注意してください-もっとすべてgitからインストールされています:

#!/usr/bin/env ruby -Ku

# encoding: utf-8

require 'rubygems'
require 'dm-core'
require 'dm-aggregates'

DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, 'sqlite3::memory:')

class Account
  include DataMapper::Resource

  property :id,        Serial
  property :name,      String
  property :acct_type, String

  has n, :account_entries

  def self.income_accounts
    all(:acct_type => 'Income')
  end
end

class AccountEntry
  include DataMapper::Resource

  property :id,               Serial
  property :description,      String
  property :amount,           BigDecimal
  property :transaction_date, Date

  belongs_to :account
end

DataMapper.auto_migrate!

account = Account.create(
  :name      => 'Test Account',
  :acct_type => 'Income'
)

5.times do |n|
  account.account_entries.create(
    :description      => "Account Entry #{n}",
    :amount           => 1.00,
    :transaction_date => Date.today
  )
end

puts Account.income_accounts.account_entries(:transaction_date.gte => Date.today - 30).sum(:amount).to_s('F')  # => 5.0

上記のプログラムを実行して、何が返されるか教えていただけますか?5.0以外のものを入手した場合は、最新のパッケージに更新して再試行してください。

于 2009-10-25T02:31:01.330 に答える
0

ユーザーエラー。の時間形式を使用するためにto_sonをいじくり回しました。削除すると、連鎖集計は予想どおりに機能しました。 DateTimestrftime

于 2009-10-24T21:25:10.577 に答える
0

DateTime は、基本単位Date.today - 30が 30前であるため、秒を使用します。試すDate.today - 30.days

于 2009-10-24T19:47:51.140 に答える
0

DateTime.now-30 または Time.now-30*3600*24 の代わりに Date.today-30 を試しましたか?

于 2009-10-24T21:10:38.047 に答える