轨道连接has_many关系,但也希望结果没有关系



我不确定实现以下目标的最佳方法:

我们有属于一个国家/地区的用户。然后,我们有几个类别,可以针对每个国家/地区进行不同的定位。

我想得到一个数组,其中包含给定国家/地区的所有类别及其位置(按 category_position.position 排序,然后按 category.name 排序)。我还希望列表包含未添加category_position的类别。

我有以下结构:

class Country < ApplicationRecord
  has_many :category_position
class Category < ApplicationRecord
  has_many :category_position
class CategoryPosition < ApplicationRecord
  attr_accessible :country_id, :position, :category_id
  belongs_to :country
  belongs_to :category

我试过使用

categories = Category.joins(:category_position)
        .where("category_positions.country_id = #{user.country.id}")

这给了我所有为用户国家/地区添加了位置的类别。我如何获得相同的列表,以及没有为用户国家/地区添加位置的所有类别?

理想情况下,此列表应按位置 (1,2,3) 排序,然后按名称(如果位置相等)排序,并按列表类别的末尾排序,没有位置。

我还没有测试过这个,但我认为你必须使用左外部连接调整 where 子句

对于导轨 5

categories = Category.left_outer_joins(:category_position)
                     .where("category_positions.country_id = #{user.country.id} or category_positions.country_id is NULL")

适用于 Rails 4 及更早版本

categories = Category.joins("left outer join category_positions on category_positions.category_id = categories.id")
                     .where("category_positions.country_id = #{user.country.id} or category_positions.country_id is NULL")

相关内容

最新更新