2013-01-02 26 views
0

我希望在每次加載頁面(現在)過濾器運行之前檢查一個項目是否超過7天,如果是,則運行一些操作它更新其屬性。Rails - 使用before_filter運行方法

我在應用程序控制器中有before_filter :update_itupdate_it是在同一個控制器中定義低於爲:

def update_it 
    @books = Book.all 
    @books.each do |book| 
    book.update_queue 
    end 
end 

然後update_queue書中模型定義。這裏的一切,涉及到這個模型:

scope :my_books, lambda {|user_id| 
    {:conditions => {:user_id => user_id}} 
    } 

    scope :reading_books, lambda { 
    {:conditions => {:reading => 1}} 
    } 

    scope :latest_first, lambda { 
    {:order => "created_at DESC"} 
    } 


    def move_from_queue_to_reading 
    self.update_attributes(:queued => false, :reading => 1); 
    end 

    def move_from_reading_to_list 
    self.update_attributes(:reading => 0); 
    end 

    def update_queue 
    days_gone = (Date.today - Date.parse(Book.where(:reading => 1).last.created_at.to_s)).to_i 

    # If been 7 days since last 'currently reading' book created 
    if days_gone >= 7 

     # If there's a queued book, move it to 'currently reading' 
     if Book.my_books(user_id).where(:queued => true) 
      new_book = Book.my_books(user_id).latest_first.where(:queued => true).last 
      new_book.move_from_queue_to_reading 
      currently_reading = Book.my_books(user_id).reading_books.last 
      currently_reading.move_from_reading_to_list 

     # Otherwise, create a new one 
     else 
      Book.my_books(user_id).create(:title => "Sample book", :reading => 1) 

     end 
    end 
    end 

我的關係是一本書belongs_to的用戶和用戶的has_many書。我通過用戶展示視圖在視圖中展示這些書籍,但不是它很重要。

所以我一直得到的錯誤是move_from_queue_to_readingmove_from_reading_to_list是未定義的方法。怎麼會這樣?我清楚地定義它們,然後在下面調用它們。我真的很茫然,非常感謝對我做錯了什麼的一些瞭解。在這裏我是初學者,所以任何結構性的批評將是巨大的:)

編輯

確切的錯誤信息,我得到和堆棧跟蹤如下:

NoMethodError in UsersController#show 
undefined method `move_from_queue_to_reading' for nil:NilClass 

app/models/book.rb:41:in `update_queue' 
app/controllers/application_controller.rb:22:in `block in update_it' 
app/controllers/application_controller.rb:21:in `each' 
app/controllers/application_controller.rb:21:in `update_it' 
+0

您能查看'new_book'和'currently_reading'變量不'nil'? – PinnyM

+0

這兩種方法是不是在'protected'或'private'部分找不到的? –

+0

@PinnyM''new_book'''如果我在控制檯中運行'''new_book = Book.where(:queued => true).last''',那麼它就不是囉嗦了。它會返回一本書。與'''current_reading'''一樣的東西。 –

回答

1

我懷疑返回的集合是一個空數組(當測試時它仍然是'truthy')。所以調用.lastnil返回給new_bookcurrently_reading局部變量。嘗試改變:

if Book.my_books(user_id).where(:queued => true) 

到:

if Book.my_books(user_id).where(:queued => true).exists? 

此外,你發現currently_reading當修改的範圍。這可能會導致查詢再次返回沒有結果。變化:

currently_reading.move_from_reading_to_list 

到:

currently_reading.move_from_reading_to_list if currently_reading 
+0

感謝您的回答。仍然得到未定義的方法。 –

+0

你可以發佈堆棧跟蹤的確切錯誤消息嗎? – PinnyM

+0

查看更新後的問題 –