如何探索ActiveRecord关系的结果?

时间:2015-11-26 05:31:43

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

这就是我在做的事情:

[72] pry(main)> Connection.joins(:inviter_memberships).where(inviter_memberships: { invited: c.inviter_membership.invited })
=> #<Connection::ActiveRecord_Relation:0x3fe19aa2ce28>

但不确定如何探索以查看哪些记录适用于该关系。

我有一个Connection模型,它具有以下关联:

# == Schema Information
#
# Table name: connections
#
#  id                    :integer          not null, primary key
#  membership_id         :integer
#  invited_membership_id :integer
# truncated for brevity

class Connection < ActiveRecord::Base
  belongs_to :inviter_membership, class_name: "Membership", foreign_key: "membership_id"
  belongs_to :invited_membership, class_name: "Membership", foreign_key: "invited_membership_id"    
end

我有一个Membership模型,如下所示:

class Membership < ActiveRecord::Base
  belongs_to :inviter, class_name: "User", foreign_key: "user_id"
  belongs_to :invited, class_name: "User", foreign_key: "invited_id"
  has_many :connections, dependent: :destroy
end

1 个答案:

答案 0 :(得分:1)

#<Connection::ActiveRecord_Relation:0x3fe19aa2ce28>表示您的查询有问题,更多信息here

关于探索查询结果: 好吧,您可以通过两种方式查看,更容易在查询结束时添加.all,另一种方法是在提示中执行以下操作

Connection.joins(:inviter_memberships).where(inviter_memberships: { invited: c.inviter_membership.invited }).each do |record|
  puts "---------"
  puts record
end

使用firstsecondthirdlast会显示您正在应用的查询,然后您可以查看并调试错误的内容查询