0

我已經創建了一個啓發我的問題的示例應用程序。has_many:通過關聯反向添加兩次

基本上,我有一個STI類許多一對多關聯關係:

class Basket < ActiveRecord::Base 
    has_many :basket_fruits, inverse_of: :basket 
    has_many :fruits, through: :basket_fruits 

    has_many :apples, through: :basket_fruits, source: :fruit, class_name: 'Apple' 
    has_many :oranges, through: :basket_fruits, source: :fruit, class_name: 'Orange' 
    has_many :bananas, through: :basket_fruits, source: :fruit, class_name: 'Banana' 
end 

class BasketFruit < ActiveRecord::Base 
    belongs_to :basket, inverse_of: :basket_fruits 
    belongs_to :fruit, inverse_of: :basket_fruits 

    validates :basket, :fruit, presence: true 
end 

class Fruit < ActiveRecord::Base 
    has_many :basket_fruits, inverse_of: :fruit 
    has_many :baskets, through: :basket_fruits 

    validates :type, presence: true, inclusion: ['Apple', 'Banana', 'Orange'] 

    validates :baskets, presence: true 
end 

class Apple < Fruit; end 
class Banana < Fruit; end 
class Orange < Fruit; end 

模式:

Basket(id: integer, created_at: datetime, updated_at: date time) 
BasketFruit(id: integer, fruit_id: integer, basket_id: integer, created_at: datetime, updated_at: date time) 
Fruit(id: integer, type: string, created_at: datetime, updated_at: datetime) 

當使用ActiveAdmin創建一個新的香蕉,它使用的代碼,這相當於到:

Basket.create 
banana = Basket.first.bananas.build(basket_ids: [Basket.first.id]) 

發生的問題是,此代碼創建兩個關聯,其中ca n即使不保存香蕉也可以觀察到:

banana.basket_fruits.size 
=> 2 

爲什麼會發生這種情況,以及如何解決它?

更新

剛剛發現這一點。也許這就是爲什麼AR正試圖增加兩倍的關係,而不是「壓倒一切」,因爲我本來期望:

banana = Basket.first.bananas.build 
=> #<Banana id: nil, type: "Banana", created_at: nil, updated_at: nil> 

banana.baskets 
=> #<ActiveRecord::Associations::CollectionProxy []> 

在這種情況下,一個需要填補了電話後,聯想前到#build

回答

2

你爲什麼分配籃子兩次?

Basket.first.bananas.build(basket_ids: [Basket.first.id]) 

我會寫這篇文章是這樣的:

Basket.first.bananas.build 
+0

驗證阻止我這樣做。 – ybart