【问题标题】:Rails eager load association with selected attributesRails 急切加载与选定属性的关联
【发布时间】:2013-03-12 09:59:05
【问题描述】:

谁能告诉我是否可以预先加载关联但只返回特定属性?

我想用他们的帐户检索一些订单,但只需要帐户名称。

Order.select([:id, :account_id]).includes(:account).limit(2)

【问题讨论】:

  • 我不确定这是否可行。但是,您可以将 account_name 添加到返回的订单记录中。 orders = Order.joins(:account).select('orders.id, orders.account_id, accounts.name AS account_name')。然后只需使用account_name 就像orders.first.account_name
  • 这是我从谷歌研究中得出的结论,感谢您的确认

标签: ruby-on-rails ruby-on-rails-3 eager-loading


【解决方案1】:

我认为 jvnill 的评论说明了一切:

我不确定这是否可能。但是,您可以将 account_name 添加到返回的订单记录中。

orders = Order.joins(:account).select('orders.id, orders.account_id, accounts.name AS account_name')

然后只使用 account_name,如 orders.first.account_name

【讨论】:

  • 我也很好奇这个。没有任何方法可以只加载特定的列或任何 find_by_sql 技巧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
相关资源
最近更新 更多