字符串转换为在数量where子句

问题描述:

我有以下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

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

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

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

为后人我想补充这些cast solutions作为答案也是:

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