Rails Rails 里面如何设计这个 association

kkeys · 2013年10月26日 · 最后由 kkeys 回复于 2013年11月13日 · 2725 次阅读

我有一个 user model 和 topic model 然后, user has many topics topic belongs to user 这个很好理解

现在我想实现 watch 功能 所以,topic 和 user 又多了个多对多的关系 topic 可以有多个关注者, user 可以有多个关注对象

这个关系怎么实现

弄个中间表 来表示多对多关系啊

Acts as follower

#2 楼 @Levan #1 楼 @shooter

没看懂,不过我在试着用中间表的方法

@Levan 貌似 follower 是通过中间表实现自关联,楼主的需求貌似是需要 user 需要有两个 has_many topics,但不知道怎么实现。看看 has_many 的文档就好,可以用不同的名字,然后指定目标类,不要依赖 rails 自己的 coc 就好

话说,如果我想限定数量,比如一个用户只能 watch 一定数量的 topic,用代码校验或是数据库触发器控制吗?

class Following < ActiveRecord::Base
  attr_accessible :follow_id, :follow_type, :user_id

  belongs_to :user
  belongs_to :follow, :polymorphic => true
end

class User < ActiveRecord::Base
    has_many :followers, :as => :follow, :class_name => "Following"
end

class Topic < ActiveRecord::Base
   has_many :followers, :as => :follow, :class_name => "Following"
end

问题已经解决

#7 楼 kaka 方案不错~~~

@toctan 懂了没?

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