0

我在用户和他们订阅的频道之间有一个多对多的关系。但是当我查看用户和用户频道或频道和用户频道之间的模型依赖关系时,用户和频道之间存在直接联系。我如何将用户频道放在两个之间?用户模型

class User < ActiveRecord::Base

  acts_as_authentic

  ROLES = %w[admin  moderator subscriber]

  has_and_belongs_to_many :channels
  has_many :channel_mods
  named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0 "} }
  def roles  
    ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }  
  end

  def roles=(roles)  
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum  
  end

  def role_symbols
    role.map do |role|
      role.name.underscore.to_sym
    end
  end





end

渠道模型

class Channel < ActiveRecord::Base
  acts_as_taggable
  acts_as_taggable_on :tags
  has_many :messages
  has_many :channel_mods
  has_and_belongs_to_many :users

end

用户渠道模型

class UsersChannels < ActiveRecord::Base
end
4

2 回答 2

2

请参阅Rails 指南上的has_many :through 文档has_many,该文档将指导您配置与中间模型的关系。

于 2010-12-02T19:21:35.250 回答
1

HABTM 关系自动生成 UsersChannels - 如果您想访问链接表的模型(添加更多属性,例如 time_channel_watched 或其他),您必须更改模型(并明确定义和迁移具有属性 id:primary_key、user_id:integer、channel_id:integer) 的 UsersChannel 模型:

class Channel < ActiveRecord::Base 

  has_many :users_channels, :dependent => :destroy
  has_many :users, :through => :users_channels  

end 


class User < ActiveRecord::Base 

  has_many :users_channels, :dependent => :destroy
  has_many :channels, :through => :users_channels 

end

class UsersChannels < ActiveRecord::Base
  belongs_to :user
  belongs_to :channel

end

注意:由于您定义的是自己的链接模型,因此您不必保留 HABTM 定义的 UsersChannels 表名称 - 您可以将模型名称更改为“Watches”之类的名称。以上所有内容几乎都在提到的 Rails 指南中。

于 2010-12-03T15:32:16.363 回答