【发布时间】:2019-10-18 13:33:17
【问题描述】:
我是新来的,也是 Rails 的新手。我目前正在尝试为我的培训项目的数据库(书籍)创建自己的搜索功能。我不想实现现有的搜索表单,因为我只想学习。 到目前为止它正在工作,但现在我添加了一个下拉菜单来从中选择一个比较符号。基于此,它会找到带有评级(“==”、“>=”或“
我尝试在整个 where 部分之前设置 if 子句,但这意味着我需要将整个 where 部分设置三次。我希望有更短的方法来实现这一目标? 提前谢谢!
def self.advanced_search(s_name, s_author, s_comp_sign, s_rating)
where("lower(name) LIKE ?", "%#{s_name}%").
where("lower(author) LIKE ?", "%#{s_author}%").
where(:rating == s_rating) #if s_comp_sign == "="
where(:rating >= s_rating) #if s_comp_sign == ">"
where(:rating <= s_rating) #if s_comp_sign == "<"
end
【问题讨论】:
-
q = M.where(a).where(b)等价于q = M.where(a); q = q.where(b)。
标签: ruby-on-rails if-statement where