0

这是我的模型:

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

这是我想要实现的查询:

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`

这是我所拥有的:

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

但这给了我错误:

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

如何使用活动记录实现上述查询?

4

1 回答 1

1

我不确定您的目标查询的目标是什么,因为它正在从所有涉及的表中选择所有字段。你期望@result包含什么?

我认为这与您希望建立关系的方式一致。

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
于 2013-04-10T23:07:43.623 回答