Rails试图加入3个表

时间:2013-04-10 22:48:35

标签: ruby-on-rails ruby ruby-on-rails-3

这是我的模特:

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?

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

1 个答案:

答案 0 :(得分: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