2012-07-05 48 views
1

我使用Ruby和我在我的对象类创建了几个范围,但是当我把他们从我的代码中返回一个错误:声明范围不on Rails的3个工作

irb>Transaction.first.committed

=> undefined method `commited' for #

对象类:

class 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") 

end

回答

0

您无法在单个事务对象(实例)上调用作用域(类方法)。

你将不得不这样做:

Transaction.committed 

你回来的ActiveRelation(基本上是Array,但你可以调用它的其他范围)。

你会期望Transaction.first.committed做什么,反正呢?你有一个单一的对象,然后你会试图找到它的transaction_type“承诺”。你已经有了这个对象,所以你可以调用它的#transaction_type方法。

范围将带回全部事务类型为已提交的事务对象。如果你想要一个实例方法,告诉你,如果对象承诺,那么你就必须做出这样一个实例方法:

def committed? 
    transaction_type == "committed" 
end 

然后,你可以写:

Transaction.first.committed? # => true 
+0

感谢您的帮助球员。 – 2012-07-05 18:10:44

0

Transaction.first将返回一个Transaction对象,所以你不能打电话给where。尝试:

Transaction.committed.first