RobotEyes
RobotEyes

Reputation: 5250

Getting ActiveRecord associations belongs_to through

I have models associated with has_many through. I am able to get a relationship in one direction but not the other (there is no belongs_to through setting)

Projects have_many datasets through taskflows. Taskflows are associated to datasets in a join table.

I am able to do Project.datasets simply by using the has_many through setting. I'd also like to call dataset.project to get the associated project of a dataset (through taskflow).

Is this possible? Many thanks for any help.

I have four models (I've tried the delegate setting but it doesn't seem to work):

class Project < ActiveRecord::Base
  validates :title, presence: true, length: {minimum: 3}
  has_many :taskflows
  has_many :datasets, :through => :taskflows
end

class Taskflow < ActiveRecord::Base
  belongs_to :project
  has_many :dataset_assignments
  has_many :datasets, :through => :dataset_assignments
end

class Dataset < ActiveRecord::Base
  has_many :dataset_assignments
  has_many :taskflows, :through => :dataset_assignments
  delegate :project, :to => :taskflows, :has_nil =>true
end

class DatasetAssignment < ActiveRecord::Base
  belongs_to :dataset
  belongs_to :taskflow
end

Upvotes: 0

Views: 34

Answers (1)

MageeWorld
MageeWorld

Reputation: 402

has_many_through works both ways.

If you put the has_many_through in reverse in your Dataset Model it should work as you wish.

A good example I use - and I learned on

  1. Recipe Model
  2. Ingredient Model
  3. Component Model

A Recipe has many ingredients through components An Ingredient has many recipes through components.

In my limited experience with it, your logic makes sense, the has_many through usually flows 'one way' in terms of creation, but in terms of rails it's the same relation type - an ingredient 'has_many' recipes through the components

Upvotes: 1

Related Questions