【问题标题】:Many to many relationship , rails多对多关系,rails
【发布时间】:2010-12-02 19:16:17
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails many-to-many relationship subscription


    【解决方案1】:

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

    【讨论】:

    • 谢谢,你能不能指出我使用控制器和视图创建这些连接的地方?
    【解决方案2】:

    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 指南中。

    【讨论】:

    • 使用 hmt 而不是 habtm 更好的做法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多