2017-10-16 79 views
1

我有以下where子句:字符串轉換爲在數量where子句

OnlineCourseRegistration.where(course_class_id: 6, status: "Completed") 
=> #<OnlineCourseRegistration id: 142, cart_id: 150, user_id: 7069, course_class_id: 681, created_at: "2017-07-15 22:06:06", updated_at: "2017-07-20 23:59:01", exam_attempts: 1, exam_completed_at: "2017-07-20 23:57:32", evaluation_completed_at: "2017-07-20 23:59:01", status: "Completed", score: "87", add_extension: false, retest_cart_id: nil, retest_purchased_at: nil> 

我還想補充一點,比分會是大於70,所以像...

OnlineCourseRegistration.where(course_class_id: 681, status: "Completed", :score.to_i > 70).last 

...但當然,這是行不通的。在where子句中有沒有辦法做到這一點?

+0

https://apidock.com/rails/ActiveRec ord/QueryMethods /其中 – krishnar

回答

2

ActiveRecord的地方接受string作爲查詢構造

OnlineCourseRegistration.where("course_class_id = ? AND status = ? AND score > ?", 681, "Completed", 70).last 
+0

這工作......謝謝!我確實需要調整一下。因爲分數是一個字符串,我不得不在分數上加上引號「OnlineCourseRegistration.where」(「course_class_id =?AND status =?AND score>?」,681,「Completed」,「70」)' – Lumbee

0

如果你不喜歡使用原始SQL可以使用阿雷爾方法,例如:

OnlineCourseRegistration.where(course_class_id: 681, status: "Completed").where(OnlineCourseRegistration.arel_table[:score].gt(70)).last 
0

爲後人我想補充這些cast solutions作爲答案也是:

where("score::int >= ?", 80)   # PostgreSQL-specific casting syntax 
where("cast(score as int) >= ?", 80) # Standard SQL type cast