1

I have two classes

class Project < ActiveRecord::Base
  has_many :related_projects
  has_many :projects, through: :related_projects
end

class RelatedProject < ActiveRecord::Base
  belongs_to :project
  belongs_to :related_project, class_name: 'Project', foreign_key: 'related_project_id'
end

RelatedProject is the association table that stores projects that are related to each other. Essentially project has a many-to-many relation to itself.

What I can't figure out is how to set this up so I can say something like

project.project_ids = [2,3] which would update a project to have two related projects. It should automatically add the association on save. This works fine if I am not doing a many to many relationship to the same model.

What am I missing?

Ryan-Neal Mes
  • 6,003
  • 7
  • 52
  • 77
  • I found the solution http://stackoverflow.com/questions/3396831/rails-many-to-many-self-join also have a look at http://guides.rubyonrails.org/association_basics.html#self-joins – Mikhail Janowski Jan 19 '15 at 20:09

1 Answers1

0

If I understand you correctly, I think you need to use has_and_belongs_to_many which will create a many to many association table. This will essentially replace your RelatedProject model.

Look at the docs for that relation.

fiskeben
  • 3,395
  • 4
  • 31
  • 35