0

Here is my code for checking boolean (i am using sqlite)

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

Apparently it looks ugly.

I tried

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

and

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

They both are not working. Is there a better way to check boolean with where in rails ?

2
  • 2
    try this : Swimming::Classstudent.where("swimming_classtimes.date >= ? and student_id = ?",current_date,student_id).where(:deleted => false) or this : Swimming::Classstudent.where("swimming_classtimes.date >= ? and student_id = ? and deleted = ? ",current_date,student_id, false) Commented Dec 13, 2013 at 4:07
  • @Taiki I have tried second one it works! Commented Dec 13, 2013 at 4:12

1 Answer 1

3

My suggestion would be to breakdown your query into reusable scopes. Code below is for 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

Usage:

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

This is questionable because I don't really have your application in front of me. Personally, I don't like swimming_classtimes join table in the after_or_on scope. Point is, when your queries start to get out of hand, extract the different clauses into scopes. It will make for much more readable, flexible, and testable code.

** might need a bit of tweaking so let me know if you decide to go this route and have any trouble **

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.