Arel通过关联查询

时间:2011-04-27 18:18:10

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

以下是我的模特:

class Player < ActiveRecord::Base
  has_many :registrations, :class_name => "PlayerRegistration"
end

class PlayerRegistration < ActiveRecord::Base
   belongs_to :player

   belongs_to :payment

   def self.paid
     where("payment_id IS NOT NULL")
   end

   def self.unpaid
     where(:payment_id => nil)
   end
end

class Payment < ActiveRecord::Base
  has_many :registrations, :class_name => "PlayerRegistration"
end

我想要做的是在Player上创建一个范围,返回所有未付注册的玩家,如下所示:

可恶的PSUEDO代码

class Player < ActiveRecord::Base

  def self.paid
    registrations.unpaid  #But actually return the players
  end
end

这可能吗?必须是,考虑到我需要的所有数据都在那里,我根本不知道如何编写那种AREL查询。有人可以帮忙吗?

FWIW我试过这个:

class Player < ActiveRecord::Base
  def self.paid
    includes(:registrations).where("registrations.payment_id IS NOT NULL")
  end
end

但是这给我提供了以下错误:

ActiveRecord::StatementInvalid:
   PGError: ERROR:  missing FROM-clause entry for table "registrations"
   LINE 1: ...registrations"."player_id" = "players"."id" WHERE "registrat...
                                                                ^
   : SELECT "players"."id" AS t0_r0, "players"."first_name" AS t0_r1, "players"."last_name" AS t0_r2, "players"."birthday" AS t0_r3, "players"."gender" AS t0_r4, "players"."created_at" AS t0_r5, "players"."updated_at" AS t0_r6, "players"."user_id" AS t0_r7, "player_registrations"."id" AS t1_r0, "player_registrations"."player_id" AS t1_r1, "player_registrations"."grade_id" AS t1_r2, "player_registrations"."shirt_size_id" AS t1_r3, "player_registrations"."division_id" AS t1_r4, "player_registrations"."coach_request" AS t1_r5, "player_registrations"."buddy_request" AS t1_r6, "player_registrations"."created_at" AS t1_r7, "player_registrations"."updated_at" AS t1_r8, "player_registrations"."league_id" AS t1_r9, "player_registrations"."season_id" AS t1_r10, "player_registrations"."school_id" AS t1_r11, "player_registrations"."payment_id" AS t1_r12 FROM "players" LEFT OUTER JOIN "player_registrations" ON "player_registrations"."player_id" = "players"."id" WHERE "registrations"."payment_id" IS NULL

有人能告诉我一个更好的方法吗?有没有办法可以使用我在PlayerRegistrations中已经拥有的付费范围?

2 个答案:

答案 0 :(得分:4)

您需要where()过滤器中的实际表名:

class Player < ActiveRecord::Base
  def self.paid
    includes(:registrations).where("player_registrations.payment_id IS NOT NULL")
  end
end

答案 1 :(得分:1)

你可以写:

class Player

  scope :unpaid, includes(:registrations).where("player_registrations.payment_id is null")
  scope :paid, includes(:registrations).where("player_registrations.payment_id is not null")

end

现在Player.unpaid将返回所有未付注册的玩家。

如果您写的内容如下:

class Registration

  scope :paid, where("payment_id IS NOT NULL")
  scope :unpaid, where("payment_id is null")

end

然后可以写player1.registrations.unpaid,但这不是你想要的。 如果我理解正确,您希望找到具有未付费注册的所有玩家,并且只能使用Player类的范围。

希望这有帮助。