【问题标题】:Convert Rails method to chainable scope将 Rails 方法转换为可链接范围
【发布时间】:2017-09-09 09:32:44
【问题描述】:

我的网站上有一个页面,允许人们根据一些条件过滤汽车。这些条件通过参数传递。

我想添加一个新条件,但模型中执行此操作的逻辑是一种方法。我无法将它添加到我的控制器过滤逻辑中,因为这完全基于 Active Record 查询和可链接部分。

如何将以下方法转换为与过滤器逻辑中的查询和链兼容的方法?

方法:

  def self.new_cars_in_year(year)
    new_cars = []

    Car.all.includes(:drives).each do |car|
      years_driven_car = []
      c = car.drives.where("date IS NOT ?", nil)

      c.each do |drive|
        years_driven_car << (Date.parse drive.date).year
      end

      years_driven_car = years_driven_car.uniq

      if car.unknown_drives
        years_driven_car.shift
      end

      if years_driven_car.min == year
        new_cars << car
      end
    end

    new_cars
  end

架构:

ActiveRecord::Schema.define(version: 20170816154910) do
  create_table "cars", force: :cascade do |t|
    t.text     "notes",                     limit: 65535
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "slug",                      limit: 255
    t.string   "covering",                  limit: 255
    t.text     "style",                     limit: 65535
    t.text     "model",                     limit: 65535
    t.float    "speed",                     limit: 24
    t.boolean  "unknown_drives"
  end

  create_table "drives", force: :cascade do |t|
    t.integer  "car_id", limit: 4
    t.string   "notes",      limit: 255
    t.string   "date",       limit: 255
    t.datetime "created_at",             null: false
    t.datetime "updated_at",             null: false
  end
end

谢谢

编辑:

【问题讨论】:

  • 你能添加你的模型和/或模式来尝试复制你的场景吗?
  • @SebastiánPalma 添加了数据库架构。谢谢

标签: ruby-on-rails activerecord named-scope


【解决方案1】:

在我看来,问题是你想要一个 Car 集合,但如果汽车在特定年份之前没有被驾驶过,则过滤掉。所选年份可能有多个“驱动器”,因此您需要汇总驱动器发生的年份。

如果这是 SQL,它会是这样的:

select cars.* from cars inner join drives on drives.car_id = cars.id
  where YEAR(STR_TO_DATE(`drives.date`, "%m/%d/%Y")) = <some year>
  group by cars.id

虽然我不熟悉您的应用程序,但这可以工作:

Car.joins(:drives)
  .where('year(str_to_date(`drives.date`, "%m/%d/%Y")) = ?', year)
  .uniq # Need to do distinct cars.id otherwise duplicate records

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多