【问题标题】:Basic Rails 3 question: How to sort products?Basic Rails 3 问题:如何对产品进行排序?
【发布时间】:2010-12-11 09:45:57
【问题描述】:

我有以下型号:

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 在数据库级别不存在)。

这样做的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 sql-order-by


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢!这正是我想要的!
    • 你无法相信我花了多少时间才找到这个。非常感谢!就像提醒一样,其他人可能会发现这一点:我正在使用 order(:field_name) 并且它在使用 sqlite3 的生产中运行良好,但是我的 webapp 托管在 heroku 中(使用 postgresql),这对我来说是错误@ 987654322@。使用这种语法它工作。再次感谢!
    【解决方案2】:

    见这篇文章:http://www.definenull.com/node/8

    在你的例子中:

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

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

    【讨论】:

    • 这很不错。但是,我会使用all 而不是find(:all...。我还更正了您的示例,使其具有复数表名。但这是一个很好的努力。
    猜你喜欢
    • 2019-03-31
    • 2010-12-08
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    相关资源
    最近更新 更多