如果发布为空,则查询返回记录等Rails

时间:2016-10-06 12:15:41

标签: ruby-on-rails ruby-on-rails-4

我遇到了问题,如果我使用类似查询发布一个空文本字段来搜索记录,它就会开始显示记录:

代码是:

SELECT  "question_options".* FROM "question_options" WHERE 
"question_options"."question_id" = $1 AND (quiz_id = 2 AND lower(option) like 
'%%')  ORDER BY created_at asc LIMIT 1

输出:

SELECT * FROM Clients WHERE Room = '2' AND Color = 'red'

2 个答案:

答案 0 :(得分:1)

这是SQL LIKE语句的默认行为。如果可以阻止,如下所示。

question_options = if self.answer_text.downcase.present?
  question.question_options.where("quiz_id = ? AND 
  lower(option) like ?", self.quiz_id, "%#{self.answer_text.downcase}%").first
end

答案 1 :(得分:1)

option <> ''中添加where,试试这个

where("quiz_id = ? AND lower(option) like ? AND (option <> '' OR option IS NOT NULL)", self.quiz_id, "%#{self.answer_text.downcase}%").first

希望有所帮助!