0

ユーザーとユーザーがサブスクライブしているチャンネルとの間に多対多の関係があります。しかし、ユーザーとユーザー チャネル、またはチャネルとユーザー チャネルの間のモデルの依存関係を見ると、代わりに、ユーザーとチャネルの間に直接的なつながりがあります。ユーザー チャネルを 2 つに分割するにはどうすればよいですか? ユーザーモデル

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 に答える