Question

I have a many-to-many relation between users and the channels they subscribe to. But when I look at my model dependency between user and user channels or channels and users channel instead there is a direct connection between users and channels. how do i put Users channels between to two? User Model

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

Channel Model

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

UsersChannel Model

class UsersChannels < ActiveRecord::Base
end
Was it helpful?

Solution

See the has_many :through documentation on the Rails guides which guides you through configuring a has_many relationship with an intervening model.

OTHER TIPS

The HABTM relationship generates the UsersChannels auto-magically - if you want to access the model for the link table (add some more attributes to it for example - time_channel_watched or whatever), you'll have to change the models (and explicitly define and migrate a UsersChannel model with the attributes id:primary_key, user_id:integer, channel_id:integer) to :

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

Note: since you're defining you're own link model you don't have to stay with the HABTM defined table name of UsersChannels - you could change the model name to something like "Watches". All of the above is pretty much in the Rails guide that has been mentioned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top