Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Belongs_to and has_and_belongs_to_many to the same table in Rails

Users create Programs. These can be followed/liked by other Users. However, the Program will ALWAYS have one creator.

So I need a ProgramsUsers table to map the like/follow. Would the "creator" also go as a type of relationship in that table, or could a Program also belongs_to a single specific User?

So in essence:

Program.rb

class Program < ActiveRecord::Base
  has_and_belongs_to_many :users    #Likes/Follows
  belongs_to :user                  #Creator

Is this acceptable or is this poor modeling?

like image 1000
dewyze Avatar asked Dec 19 '12 19:12

dewyze


2 Answers

I believe you can do something like this

class Program < ActiveRecord::Base
  has_and_belongs_to_many :users    #Likes/Follows
  belongs_to :creator, ::class_name => 'User', :foreign_key => 'creator_id'

This way, you can have a creator_id field on your programs table, and access it using @program.creator. Oh, and btw, it is not poor modeling.

like image 126
MurifoX Avatar answered Nov 15 '22 12:11

MurifoX


Something like this:

class Program < ActiveRecord::Base
  has_many :followings
  has_many :followers, :class_name => 'User', :through => :followings
  belongs_to :creator, :class_name => 'User', :foreign_key => 'creator_id'
like image 42
Anatoliy Kukul Avatar answered Nov 15 '22 11:11

Anatoliy Kukul