我试图从我的数据库中显示一些项目,我需要按字母顺序对它们进行排序。这是循环:Rails如何在不使用数组的情况下对模型进行排序?
@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 }
之后我抓住了一个异常说“不能使用方法'where'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"
}
你可以加入问题'@食物'的定义? –
有两件事,首先如果Food在你的应用中是一个模型,那么你可以使用Food.where(你的条件/ s).order(name::asc),其次,default_scope应该工作,如果你正确应用它,也许你正试图从控制台使用它,你还没有重新启动你的控制台或重新加载它? – Waheedi
添加@foods定义 –