mercredi 22 janvier 2020

Rails: How to create a has_many through association with an alias/cass_name

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!

Aucun commentaire:

Enregistrer un commentaire