简体   繁体   中英

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

Is there an alternative way that the functionality I need can be achieved?

By default rails does inner join. 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. Please change it if they are different

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