0

私はまだ SQL を学ぼうとしており、さまざまな属性による順序付けのヘルプを使用できます。私がやろうとしているのは、すべてproductsを取得して、最初に で、次にskusで注文することです。ただし、コレクション名と SKU 名は両方とも、外部キーによって製品テーブルに関連付けられている別のテーブルにあります。collection.namesku.name

したがって、次のようになります

product.id | collection.name | product.name | sku.name
1          | Apple           | Lateral File | A34
3          | Beaumont        | Desk         | BT450
2          | Beaumont        | Hutch        | BT451
5          | Beaumont        | Drawer       | BT452
7          | Vista           | File         | V246
6          | Waterfall       | TV Stand     | WF899

どんな助けでも大歓迎です

ここに私のモデルがあります:

product.rb

class Product < ActiveRecord::Base
  attr_accessible               :name, 
                                :title,
                                :features,
                                :collection_id,
                                :skus_attributes


  belongs_to                    :collection

  has_many                      :skus, dependent: :destroy
  accepts_nested_attributes_for :skus, reject_if: lambda { |a| a[:title].blank? }, allow_destroy: true
end

コレクション.rb

class Collection < ActiveRecord::Base
  attr_accessible   :name, 
                    :title,
                    :description

  has_many :products
end

sku.rb

class Sku < ActiveRecord::Base
  default_scope order('skus.id ASC')

  attr_accessible               :name,
                                :title,
                                :product_id

  belongs_to                    :product

end
4

2 に答える 2

0

上に投稿したものと同様の結果を得るには、次のようなものを試すことができます。

Product.joins(:collection, :skus)
       .select('products.id, collections.name, products.name, skus.name')
       .order('collections.name ASC, skus.name ASC')
于 2013-09-03T22:53:09.153 に答える