首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails 5,重构,对多个条件的优化查询

Rails 5,重构,对多个条件的优化查询
EN

Stack Overflow用户
提问于 2016-06-17 20:29:10
回答 1查看 381关注 0票数 0

我有一个Rails应用程序,我最近更新为rails 5。我有一个数据模型,看起来像这样(简化):Users可以有很多AppsUsers也可以是多个TeamMember,每个Team也可以有多个App。在App的索引视图/控制器中,我想列出他/她创建的所有用户应用程序,我还想列出所有属于Team的应用程序,UsersMember of。

我觉得有一种比我目前的实现更好、更有表现力的方法(可能是Rails 5中的一些新东西)。我当前的实现是这样的:

代码语言:javascript
运行
复制
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

那么,有没有一种更清洁、更理想的方法来做我正在做的事情呢?那看上去怎么样?

编辑

这就是我的活动模型关联是这样的:

代码语言:javascript
运行
复制
# 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)是否可以在这个用例中使用,比如:

代码语言:javascript
运行
复制
current_user.apps.or([...]])
# [...] = In not exactly sure what to put here in that case.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-17 20:38:33

我认为以下代码应该更简洁地完成这一任务:

代码语言:javascript
运行
复制
# 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替换。
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37889904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档