0

這裏是我有什麼,想要實現:「屬於」和「有很多」通過?

我有2種型號CategoryCollection

我想這個協會:

Category屬於Collection

Collection有許多Category

但我只需要這個關聯幾條記錄。 Like 100. 所以我沒有看到任何理由爲其餘100 000條記錄創建列。

我想這沒有運氣:

class Category 
    has_many :category_collection 

    # This is not a valid option 
    belongs_to :collection, through: :category_collection 

    # And this will throw 
    has_one :collection, through: :category_collection 

    # ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have 
    # a has_one :through association 'Category#collection' 
    # where the :through association 'Category#category_collection' is 
    # a collection. Specify a has_one or belongs_to association 
    # in the :through option instead. 
end 

class Collection 
    has_many :category_collection 
    has_many :categories, through: :category_collection 
end 

class CategoryCollection 
    self.table_name = 'categories_collections' 
    belongs_to :category 
    belongs_to :collection 
end 

或者,也許整個想法是錯誤的,我應該沒用列堅守?

+0

我認爲你所需要做的就是 - >'收集有很多:類別&'類別belongs_to:收集' – nik

+0

@nik是的,在這種情況下,我將得到剩餘的99k記錄無用的列。請再閱讀一次問題。 –

回答

0

Category屬於Collection意味着Category模型必須Collection基準(collection_id字段)。所以如果沒有99k無用的記錄就無法做到這一點。

但是可以定義has_one關聯。

class Category 
    has_one :category_collection 
    has_one :collection, through: :category_collection 
end 
+0

通過做'has_one'他會做什麼?你能解釋一下嗎? – nik

0

好,所以這有點髒我會說,但你可以這樣設置它。如果這完全是瘋狂的,請讓我知道。

class Category < ActiveRecord::Base 
    has_one :category_collection 
    has_one :collection, through: :category_collection 
end 

class Collection < ActiveRecord::Base 
    has_many :category_collections 
    has_many :categories, through: :category_collections 
end 

class CategoryCollection < ActiveRecord::Base 
    self.table_name = 'categories_collections' 
    belongs_to :category 
    belongs_to :collection 

    validate :only_one_category 

    def only_one_category 
    if CategoryCollection.all.pluck(:category_id).include?(category.id) 
     errors.add(:category, "can only have one collection") 
    end 
    end 
end 

驗證將確保您不能將多個集合添加到一個類別。