Rails:如何通过与 alias/class_name 关联来创建 has_many

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

我正在尝试通过关系将我的 HABTM 转换为 has_many。有时我必须以不同的方式连接相同的模型。例如为作者指定不同的角色。

对于 HABTM,我会通过声明 class_name 选项来做到这一点。就像:-

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

但是当我通过以下方式将所有内容转换为 has_many 时:

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

我得到: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?

当我加上:source

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

我得到:

uninitialized constant Project::author

我怎样才能让它工作?非常感谢您!

Understanding :source option of has_one/has_many through of Rails应该能帮到你

当您声明来源时,您并不是在声明 has_many 关系的 class,而是您用作中间人的关系的名称。在你的情况下,尝试:

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

正如上面的某人 post 所述:

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