[英]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
像这个例子: Rails对相关记录进行排序
But I want to sort 'on the fly' using a table like this RailsCast http://railscasts.com/episodes/340-datatables . 但是我想使用类似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: 如果我显然将信息放在父模型上,则该表可以很好地工作并进行排序,但是我不希望模型的DB表太宽,因此我想从关联的模型中提取示例:
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. 编辑:顺便说一句,是的,模型在正确的模型中具有适当的has_many&Emirates_to参数,并且子级中的外键与父模型正确对齐。
Edit 2: So after a bunch of debugging this is how it will look in SQL: 编辑2:因此,在一堆调试后,这就是它在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! 因此,现在只需将其转换为Rails格式即可! :)
:)
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: 鉴于您需要使用
LEFT JOIN
而不是INNER JOIN
,您需要自己指定大多数SQL,甚至使用Rails,也可以:
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: 如果可以使用
INNER JOIN
,那么这将简化为:
Product.joins(:tables).select('products.sku, orders.qty')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.