From 2fe8ebc143737390ea8ba952ad1b8ba4c82dae84 Mon Sep 17 00:00:00 2001
From: Lin Jen-Shin <godfat@godfat.org>
Date: Wed, 20 Jul 2016 18:06:35 +0800
Subject: [PATCH] We need INNER JOIN to get the right pipeline,

also added a test for checking this.
---
 app/models/project.rb            |  2 +-
 spec/requests/api/builds_spec.rb | 11 +++++++----
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/app/models/project.rb b/app/models/project.rb
index 026fff0da0c..f2e9d607967 100644
--- a/app/models/project.rb
+++ b/app/models/project.rb
@@ -431,7 +431,7 @@ class Project < ActiveRecord::Base
 
   # ref can't be HEAD, can only be branch/tag name or SHA
   def latest_successful_builds_for(ref = default_branch)
-    builds.where(pipeline: pipelines.latest_successful_for(ref)).
+    Ci::Build.joins(:pipeline).merge(pipelines.latest_successful_for(ref)).
       latest_successful_with_artifacts
   end
 
diff --git a/spec/requests/api/builds_spec.rb b/spec/requests/api/builds_spec.rb
index c2541346a51..553b432c7c7 100644
--- a/spec/requests/api/builds_spec.rb
+++ b/spec/requests/api/builds_spec.rb
@@ -256,14 +256,17 @@ describe API::API, api: true do
 
       context 'with latest pipeline' do
         before do
-          pipelines = Array.new(3).map do # creating some old pipelines
+          old_pipelines = Array.new(3).map do # creating some old pipelines
             create(:ci_pipeline, status: 'success')
           end
 
-          pipelines.reverse_each do |pipe|
-            new_build = create(:ci_build, :success, pipeline: pipe)
-            new_build.update(artifacts_file: another_artifacts)
+          old_pipelines.reverse_each do |pipe|
+            old_build = create(:ci_build, :success, pipeline: pipe)
+            old_build.update(artifacts_file: another_artifacts)
           end
+
+          wrong_build = create(:ci_build, :success, pipeline: pipeline)
+          wrong_build.update(artifacts_file: another_artifacts)
         end
 
         before do
-- 
GitLab