簡體   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