简体   繁体   中英

Rails: Sorting Associated Records Dynamically

Tried looking for a way to sort associated records from parent model, but only came up with static ways by hardcoding the sort in the model file itself. Like this example: Rails sorting associated records

But I want to sort 'on the fly' using a table like this RailsCast http://railscasts.com/episodes/340-datatables .

The table works and sorts beautifully if I have the info sitting on the parent model obviously, but I don't want my model's DB table being too wide, so I want to pull from the associated model Example:

Product.order("#{sort_column_p} #{sort_direction}").page(page).per_page(per_page)

def sort_column_p
  columns = %w[sku orders.qty]
  columns[params[:iSortCol_0].to_i]
end
def sort_direction
  params[:sSortDir_0] == "desc" ? "desc" : "asc"
end

When I try and sort this way I get this error:

ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'orders.qty' in
'order clause': SELECT  `products`.* FROM `products`  WHERE `products`.`user_id` = 
1 ORDER BY orders.qty asc LIMIT 20 OFFSET 0)


The associated Models being:
Parent: Product
Child: Order
Thanks for your help guys and girls!

Edit: Btw, yes the models have the appropriate has_many & belongs_to parameters in the correct models with the foreign key in the child being correctly lined up with the parent model.






Edit 2: So after a bunch of debugging this is how it will look in SQL:

SELECT Products.sku, Orders.qty
FROM Products
LEFT JOIN Orders
ON Products.id=Orders.product_id


So now its just a matter of getting it into Rails format! :)

Given that you need the LEFT JOIN instead of an INNER JOIN , you need to specify most of the SQL yourself, even with Rails, to wit:

Product.joins('left join orders on products.id=orders.product_id').select('products.sku, orders.qty')

If you could get by with an INNER JOIN , then this would simplify to:

Product.joins(:tables).select('products.sku, orders.qty')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM