开发者

How should I get my model's instances to belong to all users in my user model?

开发者 https://www.devze.com 2023-04-01 14:48 出处:网络
I have the following setup and I want to ensure that all brands in my brand model belong to all users in my user model. I would also like to ensure that once a brand has been created, and it belongs t

I have the following setup and I want to ensure that all brands in my brand model belong to all users in my user model. I would also like to ensure that once a brand has been created, and it belongs to all users, it will also belong to future users that sign up down the line.

Brand model

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 model

belongs_to :brand
belongs_to :user

User model

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

When I try the following in the console, it shows that currently the last brand instance only belongs to a single user and not both (there are currently 2 users that exist).

>> User.all.count
=> 2

>>BrandUser.last.user_id
=>1 #Should not belong to just 开发者_JAVA技巧the one user but both


Your models look correct, you may be able to clean up your Brand association call to:

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

As for ensuring all newly created users receive all Brand's, you could do a

class User
  after_create :associate_with_brands

  def associate_with_brands 
    self.brands = Brand.all
  end
end

or maybe look at an http://api.rubyonrails.org/classes/ActiveRecord/Observer.html


Your code should work, if you try Brand.first.users don't you get all of your users?

Either way, if every brand is associated with every user and viceversa, why don't you do try something like this:

def User > ActiveRecord::Base

  def brands
    Brand.all
  end

end

def Brand > ActiveRecord::Base

  def users
    User.all
  end

end
0

精彩评论

暂无评论...
验证码 换一张
取 消