通过多个条件/过滤器过滤Rails 3数据库查询

Rob*_*ies 4 search activerecord scope filtering ruby-on-rails

我在这里遇到了一个真正的困境,我很确定我要做的事情相对简单.基本上我有一个数据库(跟随迁移),列出了一堆学生和他们的信息.有四个列,seek_position,min_hourly,max_hourly和start_weeks,我需要能够在网站的前端进行过滤.现在,我可以弄清楚该怎么做是显示一个页面,其上列出了所有用户.我不打算在这里找一份讲义,我已经完成了我所知道的所有事情,甚至尝试了一些我并不理解的东西,试着让它发挥作用.似乎绊倒我的是找到一种同时过滤多种东西的方法.例如,向所有学生展示seek_position为"internship",min_hourly为"7",max_hourly为"10",start_weeks为"2 to 4".有任何想法吗?我在没有脚手架的情况下使用ActiveRecord在Rails 3.0.3上.谢谢 :)

我的迁移:

class CreateStudents < ActiveRecord::Migration
  def self.up
    create_table :students do |t|
      t.string :name
      t.string :email
      t.integer :phone
      t.text :bio
      t.text :resume
      t.string :seeking_position
      t.integer :min_hourly
      t.integer :max_hourly
      t.integer :start_weeks
      t.string :pic_uid

      t.timestamps
    end
  end

  def self.down
    drop_table :students
  end
end
Run Code Online (Sandbox Code Playgroud)

Pau*_*ber 21

这是一组相当简单的查询条件.您还应该查看searchlogic.它很棒,让你免于编写大量的SQL.

设置一些变量

position = "internship" 
min_hourly = 7
max_hourly = 18
start_weeks = 2..4
Run Code Online (Sandbox Code Playgroud)

然后写一些像这样的代码:

Student.find(:all,
:conditions => ["seeking_position = ? AND min_hourly = ? AND max_hourly = ?
                AND start_weeks between ?",
                position, min_hourly, max_hourly, start_weeks])
Run Code Online (Sandbox Code Playgroud)

在Rails 3中,您可以使用新where()功能

Student.where(:seeking_position => position,
              :min_hourly => min_hourly,
              :max_hourly => max_hourly,
              :start_weeks => start_weeks)
Run Code Online (Sandbox Code Playgroud)