我有以下两个模型。

class ResponseMap < ActiveRecord::Base
has_many :response, foreign_key: 'map_id', dependent: :destroy
belongs_to :reviewer, class_name: 'Participant', foreign_key: 'reviewer_id'


class Response < ActiveRecord::Base
include ResponseAnalytic

belongs_to :response_map, class_name: 'ResponseMap', foreign_key: 'map_id'


我必须加入这两个模型,并在ResponseMap中找到特定审阅者给出的响应,这样response.map_id = responseMap.id。这是我需要转换为ResponseMap模型的活动记录查询的SQL查询。

select * from response_maps as rm join responses as r on r.map_id = rm.id where rm.reviewer_id = 97


谁能帮我这个?

最佳答案

首先,您需要更正关联

class ResponseMap < ActiveRecord::Base
  has_many :responses, foreign_key: 'map_id', dependent: :destroy
  belongs_to :reviewer, class_name: 'Participant', foreign_key: 'reviewer_id'


如果您具有has_many关联,则名称应为复数。

查询

ResponseMap.joins(:responses).where(reviewer_id: 97)

10-07 19:04