【问题标题】:Returning multiple models with includes in Active Record返回包含在 Active Record 中的多个模型
【发布时间】:2013-02-19 01:29:28
【问题描述】:

我有两个模型,邀请和回复。一个邀请有多个 rsvps,而 rsvp 属于一个邀请。我想运行一个查询,该查询将返回所有邀请以及属于每个邀请的 rsvps。我想拥有属于邀请和 rsvp 的所有属性。我知道包含并一直在尝试诸如

@results = RSVP.where(user_id: 3).includes(:invitation)

但我只返回了 RSVP 的属性。理想情况下,我希望将 RSVP 所属的邀请属性添加到结果中。我错过了什么概念,或者我应该以不同的方式思考这个问题?

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3 rails-activerecord


    【解决方案1】:

    让我们假设Invitation 模型有两个字段event_nameevent_date,您希望在查询结果中访问它们。如果提供joins 子句,您可以自定义选择列表。

    RSVP.select("rsvps.*, invitations.event_name invitation_event_name, 
      invitations.event_date invitation_event_date"
    ).where(user_id: 3).joins(:invitation).each do |rsvp|    
      puts rsvp.invitation_event_name, rsvp.invitation_event_date
    end
    

    【讨论】:

    • 当我运行RSVP.select("rsvps.*, invitations.event_name invitation_event_name, invitations.event_date invitation_event_date" ).where(user_id: 3).joins(:invitation) 时,我在查询结果中没有得到邀请字段。我不知道为什么它不起作用。它确实返回了 rsvp 的所有字段。
    • 在控制台打印对象时不显示属性。您是否尝试过显式访问它们?即rsvp.invitation_event_name
    • 啊。我现在看到了。有用。为什么它不显示在 Rails 控制台中?
    • 在控制台AR中使用inspect方法来显示对象。该方法仅列出模型表中的字段。即使对象具有来自查询结果的动态属性。查看源代码了解更多详情:github.com/rails/rails/blob/…
    • 谢谢。非常感谢。
    【解决方案2】:

    RSVP.where(...) 带或不带includes(...) 将返回RSVP 对象的集合。通过包含每个 RSVP 所具有的 :invitation 关联,您可以立即为集合中的每个 RSVP 加载 :invitation。当您引用集合中的 :invitation 关联时,这可以防止为集合中的每个 RSVP 运行单独的 SELECT * FROM invitations WHERE ... 查询。

    .includes 如果您计划对集合中的对象使用关联,则只不过是一种查询优化。它将关联中的属性合并到结果集中的模型实例中。

    如果您想将关联的Invitation 中的属性包含在 RSVP 实例中,您可以使用Rails 的delegate 方法。你可以阅读它here

    在您的 RSVP 模型上,您可以执行类似的操作,列出来自 Invitation 的所需属性来代替我在下面留下的占位符。

    class RSVP < ActiveRecord::Base
    
      has_one :invitation
    
      delegate :some_invitation_attribute, :another_invitation_attribute, to: :invitation
    

    现在您可以直接在RSVP 实例上调用:some_invitation_attribute:another_invitation_attribute

    @results = RSVP.where(user_id: 3).includes(:invitation)
    puts @results.first.some_invitation_attribute # delegates the .some_invitation_attribute method call to the associated Invitation
    

    【讨论】:

    • 很遗憾,我仍然没有收到来自查询结果的邀请属性。
    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多