Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 基本Rails 3问题:如何对产品进行排序?_Ruby On Rails_Ruby On Rails 3_Sql Order By - Fatal编程技术网

Ruby on rails 基本Rails 3问题:如何对产品进行排序?

Ruby on rails 基本Rails 3问题:如何对产品进行排序?,ruby-on-rails,ruby-on-rails-3,sql-order-by,Ruby On Rails,Ruby On Rails 3,Sql Order By,我有以下型号: Product: name, shop_id (foreign key), brand_id (foreign key), price Shop: name Brand: name 这些协会是: Product: belongs_to :shop belongs_to :brand Shop: has_many :products has_many :brands, :through => :products

我有以下型号:

Product: name, shop_id (foreign key), brand_id (foreign key), price
Shop:    name
Brand:   name
这些协会是:

Product: belongs_to :shop
         belongs_to :brand
Shop:    has_many   :products
         has_many   :brands,   :through => :products
Brand:   has_many   :products
         has_many   :shops,    :through => :products
ProductsController#list
中,我想得到一份所有产品的列表,先按商店名称排序,然后按品牌名称排序

我试着做:

@products = Product.order("products.shop.name ASC, products.brand.name ASC")
但是它不起作用(我想是因为
products.shop.name
在数据库级别不存在)

正确的方法是什么?

请参阅本文:

在您的示例中:

@products = Product.find(:all,:include => [:shop, :brand], :order => 'shops.name ASC, brands.name ASC')

我自己还没有测试过这段代码,所以我不能保证它是100%的,但请尝试一下。如果不起作用,试着删除“ASC”,看看它是否运行。

奥斯汀L是对的,但他的语法有点旧。新的ActiveRecord语法更加简洁:

@products = Product.includes(:shop, :brand).order("shops.name ASC, brands.name ASC")

这很合适。我会使用
all
而不是
find(:all…
然而。我还更正了您的示例,使其具有复数表名。但这是一个很好的尝试。非常感谢!这正是我所要寻找的!您无法相信我花了多少时间才找到这个。非常感谢!只是提醒一下,以便其他人可能会发现:我在使用order(:field_name)在sqlite3的生产环境中运行良好,但在heroku(使用postgresql)托管的我的webapp中,这给我带来了错误
未定义的方法gsub for:field\u name:Symbol
。使用这种语法它工作正常。再次感谢!