我有一个Rails应用程序,我最近更新为rails 5。我有一个数据模型,看起来像这样(简化):Users
可以有很多Apps
,Users
也可以是多个Team
的Member
,每个Team
也可以有多个App
。在App
的索引视图/控制器中,我想列出他/她创建的所有用户应用程序,我还想列出所有属于Team
的应用程序,Users
是Member
of。
我觉得有一种比我目前的实现更好、更有表现力的方法(可能是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
那么,有没有一种更清洁、更理想的方法来做我正在做的事情呢?那看上去怎么样?
编辑
这就是我的活动模型关联是这样的:
# 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
我想知道Rails 5方法#or
(https://github.com/rails/rails/pull/16052)是否可以在这个用例中使用,比如:
current_user.apps.or([...]])
# [...] = In not exactly sure what to put here in that case.
发布于 2016-06-17 20:38:33
我认为以下代码应该更简洁地完成这一任务:
# using a shorter variable name
user = current_or_guest_user
# does the same thing as your first loop over teams
set1 = user.teams.includes(:apps).where("apps.user_id = ?", user.id).map(&:apps)
# does the same thing as the second loop
# (no need to check for duplicates here)
set2 = user.apps
# combine the two queries without adding duplicates
return set1 | set2
抱歉,如果这件事不能成功的话,我还没试过。
这里有几个概念:
includes
将通过关联“预加载”记录。这将通过一个查询获取所有相关记录,而不是激发单个SQL查询来获取每个查询。where("apps.user_id = ?", user.id)
根据关联记录的user_id筛选查询。这里的?
是一个变量,由user.id
替换。https://stackoverflow.com/questions/37889904
复制相似问题