Rails 4中同一模型的多列的动态搜索表单

时间:2014-07-25 14:47:10

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

我正在尝试创建一个包含多个列的搜索表单(全部来自同一个模型) 现在,如果将category列设置为特定值,我想将所有其他列的值设置为nil。像这样的东西 -

#app/models/question.rb
if (cateogry.matches => 'Exam Questions')

query = query.where("name like ? AND course like ? AND year like ?", "%#{query}%", "%#{query}%", "%#{query}%") 

else

query = query.where("name like ?","%#{query}%")

end

搜索表单是使用get方法的基本表单。

1 个答案:

答案 0 :(得分:1)

您可以使用范围。

class Question < ActiveRecord::Base
  ...

  # Scope for searching by exam
  scope :by_exam, -> (name, course, year) {
       match(:name, name).
       match(:course).
       match(:year, year)
  }

  # Scope forsearching by nma
  scope :by_name, ->(name) { match(:name, name) }

  # Helper scope for matching
  scope :match, ->(key, value) { where(arel_table[key].matches("%#{value}%"} }

end

所以在你的控制器中

if (cateogry.matches => 'Exam Questions')
     Question.by_exam(params[:name], params[:course], params[:year])
else
     Question.by_name(params[:name])
end