Catfish
Catfish

Reputation: 19284

Rails trying to join 3 tables

Here's my models:

class Template < ActiveRecord::Base
  has_many :application_fields
  has_many :application_fields_values
end

class ApplicationField < ActiveRecord::Base
  belongs_to :template
  has_many :application_fields_values
end

class ApplicationFieldsValue < ActiveRecord::Base
  belongs_to :application_field
end

Here's the query i'm trying to achieve:

SELECT `application_fields_values`.* , `application_fields`.*, `templates`.*
FROM `application_fields_values` 
  INNER JOIN `application_fields` ON `application_fields`.`id` = `application_fields_values`.`application_field_id`
  inner join `templates` on `templates`.`id` = `application_fields`.`template_id`

Here's what i've got:

@report = ApplicationFieldsValue.joins(:application_field, :template)

But it gives me the error:

Association named 'template' was not found; perhaps you misspelled it?

How can I achieve the query above using active record?

Upvotes: 0

Views: 55

Answers (1)

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

I'm not sure what your goal is with your target query because it is selecting all fields from all tables involved. What do you expect @result to contain?

I think this is along the lines of how you want your relations set up.

class Template < ActiveRecord::Base
  has_many :application_fields
  has_many :application_fields_values, :through => :application_fields
end

class ApplicationField < ActiveRecord::Base
  belongs_to :template
  has_many :application_fields_values
end

class ApplicationFieldsValue < ActiveRecord::Base
  belongs_to :application_field
  has_one :template, :through => :application_field
end

Upvotes: 1

Related Questions