【发布时间】: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