Belongs_to and has_and_belongs_to_many to the same table in Rails

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

So I need a ProgramsUsers table to display similar / follow. Will the "creator" also be considered as a relationship type in this table, or can Program also belongs_to specify one specific User ?

So essentially:

Program.rb

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

Is this acceptable or is it a bad simulation?

+8
ruby-on-rails activerecord
source share
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' 

Thus, you can have the creator_id field in the programs table and access it using @program.creator . Oh, and by the way, this is not a bad simulation.

+8
source share

Something like that:

 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' 
+3
source share

All Articles