1

Ruby on Rails 3を使用していて、オブジェクトクラスにいくつかのスコープを作成しましたが、コード内からそれらを呼び出すと、エラーが返されます。

irb> Transaction.first.committed

=>未定義のメソッドは#に対して「コミット」されています

オブジェクトクラス:

クラスTransaction<ActiveRecord:: Base

 attr_accessible :amount, :description, :published, :task_description_id, :discrete_task_id, :transaction_type

 belongs_to :discrete_task

 scope :committed, where(:transaction_type => "committed")

 scope :obligated, where(:transaction_type => "obligated")

 scope :expensed, where(:transaction_type => "expensed")

終わり

4

2 に答える 2

0

単一のトランザクション オブジェクト (インスタンス) でスコープ (クラス メソッド) を呼び出すことはできません。

これを行う必要があります:

Transaction.committed

が返されますActiveRelation(基本的にはArrayですが、他のスコープを呼び出すことができます)。

Transaction.first.committedとにかく、あなたは何をすることを期待しますか?transaction_type単一のオブジェクトがあり、それが「コミット」されている場所を見つけようとします。オブジェクトは既にあるので、その#transaction_typeメソッドを呼び出します。

スコープは、コミットされたトランザクション タイプを持つすべてのトランザクション オブジェクトを返します。単一のオブジェクトがコミットされているかどうかを示すインスタンスメソッドが必要な場合は、次のようなインスタンス メソッドを作成する必要があります。

def committed?
  transaction_type == "committed"
end

次に、次のように記述できます。

Transaction.first.committed? # => true
于 2012-07-05T16:06:52.057 に答える
0

Transaction.firstオブジェクトを返すTransactionので、それを呼び出すことはできませんwhere。試す:

Transaction.committed.first
于 2012-07-05T16:08:42.610 に答える