【问题标题】:Dynamic search form for multiple columns of the same model in Rails 4Rails 4中同一模型的多个列的动态搜索表单
【发布时间】:2014-07-25 14:47:09
【问题描述】:

我正在尝试创建一个包含多个列的搜索表单(全部来自同一模型) 现在,如果类别列设置为特定值,我想将所有其他列的值设置为 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方法的基本表单。

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 1970-01-01
      • 2014-04-18
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2011-01-03
      相关资源
      最近更新 更多