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

时间:2011-03-08 17:37:28

标签: ruby-on-rails search activerecord scope filtering

我现在处于一个真正的困境中,我很确定我要做的事情相对简单。基本上我有一个数据库(跟随迁移),列出了一堆学生和他们的信息。有四个列,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

3 个答案:

答案 0 :(得分:21)

这是一个非常简单的查询条件。您还应该查看searchlogic。它很棒,让你免于编写大量的SQL。

设置一些变量

position = "internship" 
min_hourly = 7
max_hourly = 18
start_weeks = 2..4

然后写一些这样的代码:

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

在Rails 3中,您可以使用新的where()函数

Student.where(:seeking_position => position,
              :min_hourly => min_hourly,
              :max_hourly => max_hourly,
              :start_weeks => start_weeks)

答案 1 :(得分:4)

用一个小时字段替换最小/最大每小时字段,因为每个人都希望他们的最大值为无穷大:

Student.where(:seeking_position => 'internship', :hourly => 7..10, :start_weeks => 2..4)

答案 2 :(得分:2)

在Rails 3中,您可以使用以下内容:

Student.where(:seeking_position => 'internship')

定义不同的查询。 这是一个包含更多详细信息的截屏视频:http://railscasts.com/episodes/202-active-record-queries-in-rails-3