2017-09-09 28 views
0

我在我的網站上有一個頁面,它允許人們根據多個標準過濾汽車。這些標準通過參數傳遞。將導軌方法轉換爲可鏈式範圍

我想添加一個新的標準,但模型中的邏輯是這樣的一種方法。我無法將其添加到我的控制器篩選邏輯中,因爲它都基於活動記錄查詢和可鏈接部分。

如何將以下方法轉換爲與我的過濾器邏輯中的查詢和鏈相兼容的東西?

方法:

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 

三江源

編輯:

+0

您可以將您的模型和/或模式嘗試複製你的場景? –

+0

@SebastiánPalma添加了數據庫模式。謝謝 – rctneil

回答

0

的問題,因爲我看到它是您想要的鏈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