我正在尝试显示数据库中的一些项目,我需要按字母顺序对它们进行排序。这是循环:
@foods.where(category: "#{Food::CATEGORIES[cat]}").find_each do |food|
..............
end
我尝试设置default_scope:
default_scope { order(name: :asc) }
没有做任何事情,并试图像这样排序:
@foods = @foods.sort_by{|food| food.name }
之后我发现了一个异常,说“无法使用方法”,其中'on array'。
我该怎么办?
编辑:@foods定义:class FoodsController < ApplicationController
before_action :set_food, only: [:show, :edit, :update, :destroy]
before_filter :authorize, only: [:create, :delete]
def index
@foods = Food.all
@food_categories = Food::CATEGORIES.keys.sort
# @current_category ||= params(:category)
end
....
end
编辑:这里的食品类别如果重要:
CATEGORIES = { "Dairy & Eggs" => "Dairy",
"Meat & Fish" => "Animal",
"Fruits & Vegetables" => "Plant",
"Nuts, beans & legumes" => "Nuts",
"Grains" => "Grains",
"Drinks" => "Beverages",
"Sweets & Candy" => "Sweets",
"Oils & Fats" => "Oils",
"Other" => "Other"
}
答案 0 :(得分:0)
你有“无法使用方法”,因为Food.all
会返回数组,因此只需使用@foods = Food.order(:name)
。