user2158382
user2158382

Reputation: 4510

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 backJob.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

Upvotes: 0

Views: 804

Answers (2)

Aguardientico
Aguardientico

Reputation: 7779

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

Upvotes: 1

gregates
gregates

Reputation: 6714

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.

Upvotes: 0

Related Questions