2012-07-05 28 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