私は最近、Rails 5に更新されたレールアプリを持っています。このような(簡略化された)データモデルがあります:Apps
、Users
複数のTeam
のMember
であり、各Team
は複数のApp
を有することもできる。私のApp
のインデックスビュー/コントローラでは、自分が作成したすべてのユーザーのアプリケーションを一覧表示したいと思います。Users
がMember
であるTeam
に属するすべてのアプリケーションをリストしたいと思います。Rails 5、リファクタリング、複数条件の最適なクエリ
私の現在の実装よりも、もっと良いやり方があると感じています(おそらく、Rails 5の新機能です)。これは私の現在の実装がどのように見えるかです:
ので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
を、私がやっている何をすべきか、よりクリーンで最適な方法は何ですか?それはどうやって見えるの?
編集は
これはどのように見えるか、私のアクティブモデルの団体である:Railsの5方法#or
(https://github.com/rails/rails/pull/16052)を使用することができれば、私は疑問に思う
# 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
編集2
この使用例では、次のようになります。
current_user.apps.or([...]])
# [...] = In not exactly sure what to put here in that case.
モデルの関連付けを適切な形式で貼り付けることはできますか? – oreoluwa
@oreoluwa私は今協会を追加しました。 – Anders
私は、より最適化されたアプローチが 'Arel'になると思っています。私はRails 5がまだこれ以上の良い方法を持っているとは思っていません。しかし、別の方法は、メソッドを委譲することですが、まだ最適化されていない可能性があります。 – oreoluwa