vendredi 17 juin 2016

Rails 5, refactoring, optimal query for multiple conditions

I have a rails app that I recently updated to Rails 5. I have a data model that looks like this (simplified): Users can have many Apps, Users can also be a Member of multiple Teams, each Team can also have multiple Apps. In my Apps index view / controller I want to list all the users apps that he / she have created, I also want to list all the apps that belongs to Teams that the Users is a Member of.

I have a feeling that there is a nicer and more performant way to do it than my current implementation (possibly something new in Rails 5). This is how my current implementation looks:

apps = []
# First get all the team apps where the user is a member, but haven't created the app. 
current_or_guest_user.teams.each do |team|
  team.apps.each do |app|
    unless app.user.eql?(current_or_guest_user)
      apps << app
    end
  end
end
# ... then get all the apps that the user have created. 
current_or_guest_user.apps.each do |app|
  unless apps.include?(app)
    apps << app
  end
end
# Return the apps. 
@apps = apps

So, is there a cleaner and more optimal way to do what I'm doing? And how does that look?

Edit

This is how my active model associations looks like:

# App.rb
belongs_to :user
belongs_to :team

# User.rb
has_many :apps, dependent: :destroy
has_many :teams
has_many :teams, through: :members

# Team.rb
has_many :apps, dependent: :destroy

Edit 2

I wonder if the Rails 5 method #or (https://github.com/rails/rails/pull/16052) could be used in this use case, something like:

current_user.apps.or([...]])
# [...] = In not exactly sure what to put here in that case.

Aucun commentaire:

Enregistrer un commentaire