diff --git a/app/models/project.rb b/app/models/project.rb
index 026fff0da0c69f5c4d98bdecd203a6df2c1d146f..f2e9d607967e07d6b722e382550c87f9a004d608 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 c2541346a518df4a3aa34d7c0d833774f818e8be..553b432c7c718722baae4857d176f04a173c2659 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