Rails and SQL - Joining by multiple table columns -


i'm still trying learn sql , use ordering different attributes. i'm trying products , skus , order them first collection.name, sku.name. however, both collection name , sku name in different tables associated products table foreign key.

so this

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 

any appreciated

here models:

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 

to result similar 1 posted above, try like:

product.joins(:collection, :skus)        .select('products.id, collections.name, products.name, skus.name')        .order('collections.name asc, skus.name asc') 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -