简体   繁体   English

Rails 4加入相关表 - 当某些记录没有关联时进行排序

[英]Rails 4 joining associated tables - sorting when some records don't have an association

I am using the following: 我使用以下内容:

Vehicle.joins(:supplier, :owner, :model).order("#{sort_column} #{sort_direction}")

which allows me to order the results by attributes in any of the 4 associated models. 这允许我按照4个相关模型中的任何一个中的属性对结果进行排序。 The problem is when a specific vehicle does not have an association eg a supplier, then no results are returned. 问题是当特定车辆没有关联例如供应商时,则不返回结果。 Only if all vehicles have all 3 associations will any results show. 只有当所有车辆都有3个协会时,才会显示任何结果。

Is there an alternative way that the functionality I need can be achieved? 有没有其他方法可以实现我需要的功能?

By default rails does inner join. 默认情况下,rails执行内连接。 That's why you don't see the records when there is no association. 这就是为什么在没有关联时你没有看到记录的原因。

If you want you can change the type of join by mentioning it explicitly 如果您愿意,可以通过明确提及来更改连接类型

Vehicle
.joins("LEFT JOIN suppliers on vehicles.supplier_id = suppliers.id")
.joins("LEFT JOIN owners on vehicles.owner_id = owners.id")
.joins("LEFT JOIN models on vehicles.model_id = models.id")
.order("#{sort_column} #{sort_direction}")

I guessed your table_names and foreign_key names based on the association name. 我根据关联名称猜出了你的table_names和foreign_key名称。 Please change it if they are different 如果它们不同,请更改它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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