2017-11-08 18 views
1

との結果が、私は次のことを達成するための最良の方法について確認していないとしますRailsはhas_manyの関係を結ぶだけでなく、無関係

私たちは国に所属するユーザーがいます。次に、各国ごとに異なる位置づけが可能ないくつかのカテゴリがあります。

すべてのカテゴリとその国の位置(category_position.position、次にcategory.name)の配列を取得したいと考えています。また、category_positionが追加されていないカテゴリをリストに含めたいとします。私は私の位置は、ユーザーの国のために追加されているすべてのカテゴリを与える

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

を使用してみました

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 

は、私は次のような構造を持っています。同じリストを取得するにはどのようにすればよいですか?

理想的には、このリストは、位置(1,2,3)、名前(等しい位置の場合)、およびリストのカテゴリの最後に位置なしで並べる必要があります。

答えて

2

私はこれをテストしていませんが、私はあなたがRailsの5

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

以前の

ため、where句

を調整に参加し、外側左を使用することがあると思います

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") 
+0

ありがとうございます。私は 'or category_positions.country_id is NULL'を追加しようとしましたが、位置が追加されたカテゴリだけを返します。私は 'categories = category.left_outer_joins(:category_position) .where(" category_positions.country_idがNULL ")'を試しましたが、何も返しません。 category_positionsがない複数のカテゴリがある場合でも – peroseth

関連する問題