2013-12-13 62 views
0

這裏是我的檢查布爾碼(我使用SQLite)軌道模型,其中布爾值

Swimming::Classstudent.where("swimming_classtimes.date >= ? and student_id = ? and deleted = 'f'",current_date,student_id) 

顯然,這看起來很難看。

我試圖

Swimming::Classstudent.where("swimming_classtimes.date >= ? and student_id = ? and deleted = 0 ",current_date,student_id) 

Swimming::Classstudent.where("swimming_classtimes.date >= ? and student_id = ? and deleted = false ",current_date,student_id) 

他們都沒有工作。有沒有更好的方法來檢查軌道中的where布爾值?

+2

試試這個的: 游泳:: Classstudent.where(「swimming_classtimes.date> =? Swimming_classtimes.date> =?和student_id =?並刪除=?「,current_date()和student_id =?」,current_date,student_id)。其中(:deleted => false) 或此: Swimming :: Classstudent.where ,student_id,false) –

+0

@Taiki我試過第二個它的作品! – wwli

回答

3

我的建議是將您的查詢分解爲可重用的範圍。下面的代碼是爲Rails 4

class Classstudent 

    scope :after_or_on, -> (date) { where("swimming_classtimes.date >= ?", date) } 

    scope :for_student, -> (id) { where(student_id: id) } 

    scope :active, -> { where(deleted: false) } 

end 

用法:

Swimming::Classstudent.after_or_on(current_date).for_student(student_id).active 

這是值得懷疑的,因爲我真的沒有在我面前你的應用程序。就個人而言,我不喜歡after_or_on範圍內的swimming_classtimes連接表。要點是,當你的查詢開始失控時,將不同的子句提取到範圍中。它將提供更多可讀,靈活和可測試的代碼。

**可能需要一些調整,以便讓我知道,如果你決定走這條路線,並有任何麻煩,**