【问题标题】:How should I get my model's instances to belong to all users in my user model?我应该如何让我的模型实例属于我的用户模型中的所有用户?
【发布时间】:2011-08-29 12:47:31
【问题描述】:

我有以下设置,我想确保我的品牌模型中的所有品牌都属于我的用户模型中的所有用户。我还想确保一旦创建了一个品牌,它属于所有用户,它也将属于未来注册的用户。

品牌模型

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

品牌用户模型

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

【问题讨论】:

  • 只是为了确认一下,BrandUser.count == 1?此外,您应该能够执行 self.users = User.all 而不是循环。
  • 不,BrandUser.count == 4(现在,虽然它会上升很多,比如 200)。
  • 目前有多少品牌和用户?
  • 4 个品牌和 2 个用户。奇怪的是,该协会给出了 User.first.brands.count == 3 和 User.last.brands.count == 1
  • 在下面查看我的答案,看看是否适合您

标签: ruby-on-rails ruby-on-rails-3 models has-many-through


【解决方案1】:

您的模型看起来正确,您可以清理您的品牌关联调用:

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

【讨论】:

  • 感谢 after_create 钩子是我正在寻找的。我确实意识到问题不在于我的模型,而在于我的控制器,这里stackoverflow.com/questions/7042781/… 我在那里回答了我自己的问题的第一部分,但需要过滤 (:taggings => { :id => nil } )当前用户只有 nil 标记。
【解决方案2】:

您的代码应该可以工作,如果您尝试Brand.first.users,您不会获得所有用户吗?

无论哪种方式,如果每个品牌都与每个用户相关联,反之亦然,您为什么不尝试这样的事情:

def User > ActiveRecord::Base

  def brands
    Brand.all
  end

end

def Brand > ActiveRecord::Base

  def users
    User.all
  end

end

【讨论】:

  • 第二。如果您事先知道一切都会与一切相关联,为什么还要尝试建立关联。
  • 您是否需要从用户中删除关联品牌?他们能否在创建后定制自己的品牌?
  • 谢谢。我想厨房里有太多厨师(意见)导致我这样做。 Krisitan,不回答你的问题。
猜你喜欢
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 2023-03-20
  • 2015-07-25
  • 2011-04-22
  • 1970-01-01
相关资源
最近更新 更多