2015-04-28 36 views
0

的名字這是我的模型有關聯:Rails的SQL連接兩個表,一個表與其他表的IDS兩列,我需要得到這些ID

class ProjectLineThreshold < ActiveRecord::Base 
    belongs_to :project_line 
    belongs_to :source, class_name: 'Language' 
    belongs_to :target, class_name: 'Language' 
end 

ProjectLineThreshold表中有這些列(:ID ,:source_id,:target_id,:score)。我需要通過語言表中的source_id和target_id添加語言的名稱。

我想出了這樣的說法:

thresholds = self.project_line_thresholds.joins(:source, :target) 
    .select('project_line_thresholds.id, project_line_thresholds.source_id, project_line_thresholds.target_id, 
     project_line_thresholds.score, languages.name as source_name, languages.name as target_name') 

,但我得到了目標和源相同的名稱。什麼是正確的加入聲明,或者我做錯了?

回答

1

下面的查詢將只命中了一次分貝:

self.project_line_thresholds 
    .joins(:source, :target) 
    .includes(:source, :target) 
    .map {|plt| [plt.id, plt.source_id, plt.target_id, plt.score, source.name, target.name]} 
2

你不需要select語句,只需通過協會拿到的名字:

ProjectLineThreshold.includes(:source, :target).each do |plt| 
    puts "Source name: #{plt.source.name}" 
    puts "Target name: #{plt.target.name}" 
end 

注意includes只是確保預加載相關的記錄,否則將運行單獨的查詢檢索源在循環的每次迭代期間的目標。

1

你只需要,如果你想急於加載數據的聲明,即運行一切一個SQL查詢。這個答案已經提供。

否則,你可能只使用由active record提供的關聯方法,例如:

@project_line_threshold.source.name 
@project_line_threshold.target.name