我有一個Active-record物件的串列,其中包括品牌等多個列。
[#<UsedCar id: 861214, city_id: 4, place_id: 1, description: "abc",brand: "Toyota" >,#<二手車 id: 861214, city_id: 4, place_id: 1, description: "abc",brand: "Honda">,#<二手車id: 861214, city_id: 4, place_id: 1, description: "abc",brand: "Jeep">,#<二手車id: 861214, city_id: 4, place_id: 1, description: "abc",brand: "Opel">,]
還有一個只有品牌的陣列
brands = %w[Toyota, Nissan, Lexus, Kia, Mazda, Honda, BMW, Range Rover, Chevrolet, Mitsubishi]
我想按照品牌陣列的排序來排列物件串列,但是沒有找到任何方法來使用sort_by或sort或group_by
uj5u.com熱心網友回復:
我真的建議你考慮用資料庫中的記錄來代替排序。資料庫的排序能力真的很強,你不必為了讓它按順序排列而從表中抽出每一條記錄。
你可以在SQL中這樣做:
ORDER BY
CASE WHEN brand = 'Toyota' THEN 0
WHEN brand = 'Nissan' THEN 1
...
ELSE 100 END
你可以用Arel程式化地創建SQL CASE陳述句:
cars = Car.arel_table
kase = Arel::Nodes::Case.new(cars[:brand)。
when('Toyota').then(0)。
when('Nissan').then(1)。
when('Lexus').then(2)。
Car.order(kase)
我相信你可以用Enumerable#each_with_index和Enumerable#inject將其變成一個回圈。
uj5u.com熱心網友回復:
在Rails 7中,你可以使用ActiveRecord::QueryMethods#in_order_of來構建@max建議的order by陳述句。特征PR。https://github.com/rails/rails/pull/42061/files
brands = %w[Toyota Nissan Lexus Kia Mazda Honda BMW Range Rover Chevrolet Mitsubishi] /span>
UsedCar.in_order_of(:brand, brands)
# => UsedCar加載(0.7ms) SELECT "used_cars".* FROM "used_cars" ORDER BY CASE "used_cars". "brand" WHEN 'Toyota' THEN 1 WHEN 'Nissan' THEN 2 WHEN 'Lexus' THEN 3 WHEN 'Kia' THEN 4 WHEN 'Mazda' THEN 5 WHEN 'Honda' THEN 6 WHEN ' BMW' THEN 7 WHEN ' Range' THEN 8 WHEN ' Rover' THEN 9 WHEN ' Chevrolet' THEN 10 WHEN ' Mitsubishi' THEN 11 ELSE 12 END ASC
另外,如果你有一個UsedCar物件的陣列,那么Rails 7也能滿足你的要求,因為它還添加了Enumerable#in_order_of。
used_cars = [#< UsedCar id: 861214, city_id: 4, place_id: 1, 描述。"abc", 品牌: "Toyota">, #<二手車 id: 861214, city_id: 4, place_id: 1, description: "abc", brand: "Honda">, #<二手車id: 861214, city_id: 4, place_id: 1, description: "abc", brand: "Jeep">, #<二手車id: 861214, city_id: 4, place_id: 1, description: "abc", brand: "Opel">]
used_cars.in_order_of(: brand, brands)
uj5u.com熱心網友回復:
已經有一個針對Rails 7的拉動請求來提供這樣的功能
。在此基礎上,你可以這樣做
used_cars.index_by(&:brand).values_at(*brands).compact
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/322759.html
標籤:
下一篇:訪問/使用Rails憑證的挑戰
