2011-08-29 71 views
0

我有以下設置,我想確保我的品牌模型中的所有品牌屬於我的用戶模型中的所有用戶。我還想確保一旦創建了一個品牌,並且它屬於所有用戶,它也將屬於註冊該品牌的未來用戶。我應該如何讓我的模型的實例屬於我的用戶模型中的所有用戶?

品牌型號

has_many :brand_users 
has_many :users, :through => :brand_users 

after_create :associate_with_all_users 

def associate_with_all_users 
    User.find(:all).each do |user| 
    users << user 
    end 
    save 
end 

BrandUser模型

belongs_to :brand 
belongs_to :user 

用戶模型

has_many :brand_users 
has_many :brands, :through => :brand_users 

當我嘗試在控制檯以下,這表明目前的最後一個品牌實例只屬於一個用戶而不是兩個(t目前有2個用戶存在)。

>> User.all.count 
=> 2 

>>BrandUser.last.user_id 
=>1 #Should not belong to just the one user but both 
+0

只是爲了確認,BrandUser.count == 1?你也應該能夠做self.users = User.all而不是循環。 –

+0

不,BrandUser.count == 4(現在,雖然會漲到很多,比如200)。 – Simpleton

+0

您目前有多少品牌和用戶? –

回答

2

你的模型看起來是正確的,你可以清理你的品牌協會呼籲:

def associate_with_all_users 
    self.users = User.all 
    # save I don't believe this is necessary anymore if you assign the association 
end 

是確保所有新創建的用戶收到的所有品牌的,你可以做一個

class User 
    after_create :associate_with_brands 

    def associate_with_brands 
    self.brands = Brand.all 
    end 
end 

或者看看http://api.rubyonrails.org/classes/ActiveRecord/Observer.html

+0

謝謝after_create鉤是我正在尋找。我意識到問題不在於我的模型,而在於我的控制器,這裏http://stackoverflow.com/questions/7042781/how-can-a-rails-form-b​​e-filtered-to-show-only- objects-without-tags-and-by-a-curr我在那裏回答了我自己的問題的第一部分,但需要過濾(:taggings => {:id => nil})僅爲當前用戶的零標記。 – Simpleton

2

您的代碼應該工作,如果你嘗試Brand.first.users你不給所有的用戶?

無論哪種方式,如果每個品牌與每一位用戶,反之亦然相關的,你爲什麼不嘗試做這樣的事情:

def User > ActiveRecord::Base 

    def brands 
    Brand.all 
    end 

end 

def Brand > ActiveRecord::Base 

    def users 
    User.all 
    end 

end 
+0

借調。如果你事先知道一切都會與一切有關,爲什麼要嘗試建立關聯。 –

+0

您是否曾經需要從用戶中刪除關聯的品牌?他們能夠在創建後自定義品牌嗎? –

+0

謝謝。我想廚房裏有太多的廚師(意見)讓我知道。克里斯坦,不回答你的問題。 – Simpleton

相關問題