繁体   English   中英

Rails Active Record内部联接不起作用

[英]Rails Active Record inner join not working

我有3个模型: RunnersJobsSurveys 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,但是每当我运行join_table时,它所做的只是返回Job.all 它不返回Job and Survey的联接表。 我也尝试了以下

joined_table = Job.all(:include => :survey)
joined_table = Job.all(:select => '*', :joins => :survey)
joined_table = Job.all(:joins => :assignment, :include => :survey)

这三项都不起作用

试试看:

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对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM