我应该如何让我的模型实例属于我的用户模型中的所有用户?
我有以下设置,我想确保我的品牌模型中的所有品牌都属于我的用户模型中的所有用户。我还想确保,一旦创建了一个品牌,它属于所有用户,它也将属于未来注册的用户。
品牌模型
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
当我在控制台中尝试以下操作时,它显示当前最后一个品牌实例仅属于单个用户而不是两个用户(当前存在 2 个用户)。
>> User.all.count
=> 2
>>BrandUser.last.user_id
=>1 #Should not belong to just the one user but both
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 the one user but both
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的模型看起来正确,您也许可以清理您的品牌关联调用:
至于确保所有新创建的用户收到所有品牌,您可以执行
或查看 http://api.rubyonrails.org/classes/ActiveRecord/Observer.html
Your models look correct, you may be able to clean up your Brand association call to:
As for ensuring all newly created users receive all Brand's, you could do a
or maybe look at an http://api.rubyonrails.org/classes/ActiveRecord/Observer.html
您的代码应该可以工作,如果您尝试
Brand.first.users
,您不会获得所有用户吗?不管怎样,如果每个品牌都与每个用户相关联,反之亦然,为什么不尝试这样的事情:
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: