2016-11-27 65 views
0

我试图从我的数据库中显示一些项目,我需要按字母顺序对它们进行排序。这是循环: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" 

}

+0

你可以加入问题'@食物'的定义? –

+1

有两件事,首先如果Food在你的应用中是一个模型,那么你可以使用Food.where(你的条件/ s).order(name::asc),其次,default_scope应该工作,如果你正确应用它,也许你正试图从控制台使用它,你还没有重新启动你的控制台或重新加载它? – Waheedi

+0

添加@foods定义 –

回答

0

你得“无法使用方法 '其中'因为Food.all返回数组。只需使用@foods = Food.order(:name)

+0

但它仍然没有对它进行排序: –

+0

使用原始生成的sql查询显示您的输出日志。你使用Postgres或MySQL? –

+0

你是什么意思“用原始生成的sql查询显示你的输出日志”? MySQL –

相关问题