查找数字范围(最小值 - 最大值)中包含的记录



Course.rb

min_age: integer
max_age: integer

学生年龄来自params[:age] - 例如 15,这意味着学生是 15 岁,他寻找适合他年龄的课程:

我有课程:

id    min_age   max_age
------------------------
1     5          15
2     10         25
3     10         55
4     20         40

问题:

如何找到 min_age 和 max_age 涵盖年龄参数值的所有记录?如果学生说他15岁,他应该看的课程是:

1、2 和 3,因为这些是涵盖这个年龄的人。

此外,我需要在搜索模型中使用它,当有人搜索课程并且返回的结果是用户(提供这些课程的导师)时,它会创建一个搜索记录。

  def find_courses
    users = User.joins(:courses).where("courses.lesson ILIKE ?", "%#{lesson}%")
    # failed attempt:
    users = users.where('course.min_age >= :age or courses.max_age <= :age', age: age)
  end

谢谢你的时间。

基于接受的答案:

Course.where('min_age <= :age AND max_age >= :age', age: 18)

上述 SQL 将要求两个条件都为 true 才能显示记录:

id    min_age   max_age
------------------------
1     5  true  + 15 false = false
2     10 true  + 25 true  =  true
3     10 true  + 55 true  =  true
4     20 false + 40 true  =  false

这将返回 id 为 2 和 3 的记录

更改大于/小于符号并使用 AND

Course.where('min_age <= :age AND max_age >= :age', age: 18)

您的状况应该是

def find_courses
  user_courses = User.joins(:courses).where('courses.lesson ILIKE ?', "%#{lesson}%")
  user_courses.where(':age >= courses.min_age and :age <= courses.max_age', age: age)
end

通过以更像 Rails 的方式实现资源,该结构将允许轻松查询:

在 routes.rb 中:

resources :users, only: :show do
  resources :courses, only: :index
end

在课程控制器#索引中:

@courses = current_user.available_courses

在用户模型中:

def available_courses
  Course.where('min_age <= ? and max_age >= ?', age, age)
end

同样在逻辑和可重用性方面,我建议给用户一个 date_of_birth:datetime 属性,并在用户模型中设置一个方法来返回它的年龄。

最新更新