Question

I have tried and failed to create a has_many association from a has_many :through join table e.g

class Child < ActiveRecord::Base
  has_many :relationships
  has_many :parents, through: :relationships
end

class Parent < ActiveRecord::Base
  has_many :relationships
  has_many :children, through: :relationships
end

class Relationship < ActiveRecord::Base             <------ Join table
  belongs_to :child
  belongs_to :parent
  has_many :schedules
end

class Schedule < ActiveRecord::Base
  belongs_to :relationship
end

The reason i'd like this is because a child can have many schedules however in a situation like a custody dispute or messy divorce I don't want parent 1 to see the schedule that parent 2 has given the child. A parent can of course have many children so I can't put the schedule with the Parent model.

The same parent can also have many schedules with the same child e.g one for this week and one for next week.

I have tried other strategies but this method would suit the data best so I'd like confirmation if it is impossible or not.

Thanks!

Was it helpful?

Solution

I think following should do:

class Child < ActiveRecord::Base
  has_many :relationships
  has_many :parents, through: :relationships
  has_many :schedules
end

class Parent < ActiveRecord::Base
  has_many :relationships
  has_many :children, through: :relationships
  has_many :schedules
end

class Relationship < ActiveRecord::Base
  belongs_to :child
  belongs_to :parent
end

class Schedule < ActiveRecord::Base
  belongs_to :child
  belongs_to :parent
end

EDIT: The above relation is easy to handle because it will give you schedules directly like

child_object.schedules     # All schedules of child
parent_object.schedules    # All schedules of parent

You can further filter this results by defining scopes in Schedule model

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top