2013-02-19 48 views
1

我有两个模型,Invitation和RSVP。一个邀请有很多rsvps,而rsvp属于一个邀请。我想运行一个查询,它将返回属于每个邀请的所有邀请和rsvps。我想拥有属于邀请和rsvp的所有属性。我知道包括并一直在尝试的东西,如在Active Record中返回包含多个模型

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

但我只获取RSVP返回的属性。理想情况下,我希望将RSVP所属邀请的属性添加到结果中。我错过了什么概念,或者我应该如何看待这种不同的方式?

回答

3

让我们假设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 
+0

当我运行RSVP.select(“rsvps。*,invitations.event_name invitation_event_name, invitations.event_date invitation_event_date” ).where(user_id:3).joins(:invitation)',我没有得到邀请字段在查询结果中。我不知道为什么它不起作用。它确实返回了rsvp的所有字段。 – jason328 2013-02-19 02:45:30

+1

在控制台中打印对象时,不显示这些属性。你有没有试图明确地访问它们?即'rsvp.invitation_event_name' – 2013-02-19 03:16:37

+0

啊。我现在看到了。有用。为什么不在Rails控制台中显示? – jason328 2013-02-19 03:24:29

1

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 
+0

不幸的是,我仍然没有收到来自查询结果的邀请属性。 – jason328 2013-02-19 02:29:39