【问题标题】:Build list of plucked attributes from belongs_to association从 belongs_to 关联中构建提取属性列表
【发布时间】:2017-11-09 21:01:21
【问题描述】:

Active Record 忍者,

我正在寻找一种简洁的 Rails 方法来从关联模型中获取属性。

class Team < ActiveRecord::Base
  belongs_to :captain, class_name: User

获取与团队相关联的独特队长数组:

Team.all.map(&:captain_id).uniq

我想做的是获取唯一的船长名单,并抓住每个人的first_namelast_name

我想做

Team.all.map(&:captain_id).uniq.pluck(:first_name, :last_name)

但是pluck 不适用于数组。我可以分几步完成,但 Rails 的方式是什么?

【问题讨论】:

  • 你在使用 PostgreSQL 吗?
  • User.where(id: Team.all.select(:captain_id)).pluck(:first_name, :last_name)
  • @MrYoshiji just Team.pluck(:captain_id) 也可以
  • @MrYoshiji - 是的 PostgreSQL。
  • @MrYoshiji - 您的第一个回复效果很好。把它变成一个答案,我会接受它。

标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord belongs-to


【解决方案1】:

您可以执行以下操作:

captain_ids = Team.all.select(:captain_id)
User.where(id: captain_ids).pluck(:first_name, :last_name)

Rails 应该足够聪明,可以进行嵌套选择。

另一个选项是joins,它可以更高效(更快),但在我的测试用例中,子选择比INNER JOIN 快3 倍。自己试试吧:)

【讨论】:

    【解决方案2】:

    您可以使用joinsgroup

    Team.joins(:captain)
        .group("users.id")
        .pluck("users.first_name", "users.last_name")
    

    【讨论】:

    • 即使在Team.joins(:captain).group("captains.id") 也遇到错误:ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "captains"
    猜你喜欢
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多