I think this could be a scope:
```
scope : for_repository, ->(repo) { joins(:project).where('projects.repository_id' => repo.id) }
```
The call in builds_controller.rb & project.rb would become:

```
@project.builds.for_repository(@project.repository).first_or_initialize(ref: sha)
```
This would remove: ```if existing_build```