0

I am trying to transform my HABTM to has_many through relations. Sometimes I have to connect the same models in different ways. For example to specify different roles for authors.

With a HABTM I would do this through the declaration of a class_name option. Just like:-

class Project < ActiveRecord::Base
  has_and_belongs_to_many :curators, :class_name => :author, :through => :projects_curators
end

class ProjectsCurator < ActiveRecord::Base  
  attr_accessible :project_id, :author_id
  belongs_to :project
  belongs_to :author
end

class Author < ActiveRecord::Base
 has_and_belongs_to_many :projects, :through => :projects_curators
end

But when I transform everything into a has_many through:

class Project < ActiveRecord::Base
  has_many :project_curators
  has_many :curators, :class_name => :author, :through => :project_curators
end

class ProjectCurator < ActiveRecord::Base  
  attr_accessible :project_id, :author_id
  belongs_to :project
  belongs_to :author
end

class Author < ActiveRecord::Base
  has_many :project_curators
  has_many :projects, :through => :project_curators
end

I get: Could not find the source association(s) :curator or :curators in model ProjectCurator. Try 'has_many :curators, :through => :project_curators, :source => <name>'. Is it one of :author or :project?

When I add :source

has_many :curators, :class_name => :author, :through => :project_curators, :source => :author

I get:

uninitialized constant Project::author

How can I get this working? Thank you very much in advance!

code_aks
  • 1,972
  • 1
  • 12
  • 28
SEJU
  • 995
  • 1
  • 9
  • 28

1 Answers1

3

Understanding :source option of has_one/has_many through of Rails should help you out

When you declare the source you're not declaring the class of the has_many relationship, but the name of the relationship you're using as the middle man. In your case, try:

has_many :curators, :through => :project_curators, :source => :author

As someone in the above post states:

Most simple answer - the name of the relationship in the middle

Mark
  • 6,112
  • 4
  • 21
  • 46
  • Thanks a lot @Mark. Great reference. I had to use `has_many :curators, :through => :project_curators, :source => :author`, but had `alias_attribute :curator` in author.rb, which exists only in Rails 4+ and collided with all the rest. No need for :class_name apparently. Could you edit your answer? – SEJU Jan 22 '20 at 16:30
  • 1
    I should have read more carefully :) Edited and glad it's working – Mark Jan 22 '20 at 16:48