Rails many-to-many-to-many 的关系应该怎么写?

suupic · 2011年12月26日 · 最后由 dy1901 回复于 2013年11月26日 · 3279 次阅读

例如 提案--用户组--用户这样的三层关系

其中提案 - 用户组和用户组 - 用户都是多对多

如何建立提案和用户间的关系?

匿名 #1 2011年12月26日

两个 HABTM 好了

class 提案 < ActiveRecord::Base
  has_many :用户组
  has_many :用户, through: :用户组
end

class 用户组 < ActiveRecord::Base
  has_many :用户
end

原来我用:through 一直报错是因为 mongoid 没有实现这个特性 最后参考http://groups.google.com/group/mongoid/browse_thread/thread/fd2b57f9118376c4/87730bec244a9d8c?lnk=gst&q=through#87730bec244a9d8c 解决了问题

模型关系大致如下

class Plan
  has_and_belongs_to_many :group

  def users
    group.collect { |t| t.user rescue nil }
  end
class Group
  has_and_belongs_to_many :plan
  has_and_belongs_to_many :user
class User
  has_and_belongs_to_many :group

可以用 plan.users 获取 plan 所有 group 下的用户

#3 楼 @suupic has_and_belongs_to_many 性能相当的坑人,数据上百以后经常会出现 cpu 假死。我现在是用 array 搞的,不知道各位道友有没有其他的方案。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号