我有三个模型:Runners
、Jobs
和Surveys
。Runner
为has_many
作业建模。Job
型号为has_one
Survey
。我正在尝试获取跑步者的所有调查(所有与属于特定跑步者的工作相关的调查)。
这是我的型号
runner.rb
class Runner < ActiveRecord::Base
has_many :jobs
end
job.rb
class Job < ActiveRecord::Base
belongs_to :runner
has_one :survey
end
survey.rb
class Survey < ActiveRecord::Base
attr_accessible :service, :speed, :suggestion, :job_id
belongs_to :job
end
为了为一个跑步者获得所有的工作,我打开了rails控制台,并尝试运行这样的命令。
runner = Runner.first
joined_table = Job.joins(:survey)
joined_table.where(runner_id: runner.id)
这看起来像是输出了正确的SQL,但每当我运行joined_table时,它所做的只是返回Job.all
。它不会返回Job和Survey的联接表。我还尝试了以下
joined_table = Job.all(:include => :survey)
joined_table = Job.all(:select => '*', :joins => :survey)
joined_table = Job.all(:joins => :assignment, :include => :survey)
这3个都不起作用
尝试一下:
runner.rb
class Runner < ActiveRecord::Base
has_many :jobs
has_many :surveys, through: :jobs
end
然后
runner = Runner.first
runner.surveys
我相信你想要
Survey.joins(:job).where(jobs: { runner_id: runner.id })
这将为您提供属于某个作业的所有Survey
对象,该作业属于所讨论的跑步者。