Rails和SQL - 由多个表列连接

时间:2013-09-03 22:19:52

标签: sql ruby-on-rails

我仍在尝试学习SQL,我可以使用不同属性的一些帮助排序。我要做的是获取所有productsskus并先按collection.name,然后按sku.name排序。但是,集合名称和sku名称都位于通过外键与products表关联的不同表中。

所以它看起来像这样

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

collection.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

2 个答案:

答案 0 :(得分:0)

你不会在Rails中得到那个确切的结果,因为那不是Rails的用途。但是,如果您想要按集合名称和sku名称订购所有产品,那就是

Product.joins(:collection, :skus).order('collections.name, skis.name')

但是因为在你的模型中,产品可能有很多SKU,我不能完全确定该查询的结果。

答案 1 :(得分:0)

要获得与您在上面发布的结果类似的结果,您可以尝试以下内容:

Product.joins(:collection, :skus)
       .select('products.id, collections.name, products.name, skus.name')
       .order('collections.name ASC, skus.name ASC')