2011-01-14 46 views
2

用戶有許多任務。在Rails中查找記錄(困惑於採取什麼方法)

在a任務控制器視圖中,需要爲用戶顯示任務。 (各種狀態的一個視圖 - 活動,分配,關閉等)

什麼是「正確」的方式獲取任務列表,說status = active?

#class method on Task; called from TasksController 
Task.find_for_user(current_user, :active) 

#instance method on user; called from TasksController 
current_user.find_tasks :active (user model instance) 

#the "common" way that is used in controllers and in many examples/articles 
current_user.tasks.find(:where => :status = :active) #Note the "where" part here is pseudo-code (not tested it) 

回答

1

使用該關聯是我如何接受培訓的。一直工作得很好,並讓Rails照顧SQL而無需任何額外的代碼。

所以current_user.tasks.where(:status => :active),或者你可以創建一個範圍。

app/models/task.rb

class Task < ActiveRecord::Base 
    scope :active, :conditions => { :status => :active } 
    ... 
end 

,並在控制器中調用current_user.tasks.active

也可能想看看the documentation裏面包含了很多其他不錯的提示