简体   繁体   中英

Rails Active Record inner join not working

I have 3 models: Runners , Jobs , and Surveys . The Runner model has_many jobs. The Job model has_one Survey . I am trying to get all the Surveys for a Runner (all of the surveys that are associated with jobs that belong to a particular runner).

Here are my models

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

In order to get all the jobs for a runner I opened up rails console and tried running a command like this.

runner = Runner.first
joined_table = Job.joins(:survey)
joined_table.where(runner_id: runner.id)

This looks like it outputs the correct SQL, but whenever I run joined_table, all it does is return back Job.all . It doesnt return the joined table of Job and Survey. I also tried the following

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

None of these 3 work either

Give a try to it:

runner.rb

class Runner < ActiveRecord::Base
  has_many :jobs
  has_many :surveys, through: :jobs
end

and then

runner = Runner.first
runner.surveys

I believe you want

Survey.joins(:job).where(jobs: { runner_id: runner.id })

This should give you all Survey objects which belong to a job that belongs to the runner in question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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