mysql - 从给定编号所属的表中选择所有记录

标签 mysql ruby-on-rails ruby range

假设我的模型中有以下三个记录:

#<Rda:0xf6e8a0c
 id: 1,
 age_group: "18-100",
 weight: "60",
 nutrient: "energy(kcal/day)",
 value: "2730",
 created_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00,
 updated_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00>


#<Rda:0xf6e8a0c
 id: 2,
 age_group: "10-15",
 weight: "60",
 nutrient: "energy(kcal/day)",
 value: "2730",
 created_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00,
 updated_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00>


#<Rda:0xf6e8a0c
 id: 3,
 age_group: "20-100",
 weight: "60",
 nutrient: "energy(kcal/day)",
 value: "2730",
 created_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00,
 updated_at: Sat, 15 Oct 2016 08:21:43 UTC +00:00>

现在,我想获取我的给定值落在“age_group”列范围内的所有记录。例如:假设我的年龄是 25 岁,那么我应该从上述记录中获取 ID 为 1 和 3 的记录,因为“25”介于“18-100”和“20-100”之间

最佳答案

你可能会做

def self.foo(age)
  all.select { |rda| Range.new(*rda.age_group.split('-').map(&:to_i)).cover? age }
end

关于mysql - 从给定编号所属的表中选择所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40058080/

相关文章:

ruby - 可以在 Ruby 中重新发明数组吗?

ruby - 需要所有数据库的文件 :migrate?

ruby-on-rails - 一起搜索 ID 和字符串

mysql - customer_id '在where子句中不是明确的?

php - mysqli 代码不会发送到数据库

ruby-on-rails - Cucumber/Capybara/Selenium - 设置 cookie

ruby-on-rails - rails : Passing API Keys to the Controller

mysql - 将所有记录关系移动到另一条记录

php - 检索数据库表中具有特定值的最新条目

ruby-on-rails - 在 Rails 3 中使用 MongoMapper 的回形针