ActiveRecord:链接相关记录的范围和查询

时间:2017-02-01 21:27:05

标签: mysql ruby-on-rails ruby activerecord

我遇到了一些ActiveRecord行为,我觉得这很直观,但它让我感到惊讶。给出

class User < ActiveRecord::Base
  has_one :profile

  scope :active, -> { where(status: 1) }

  def self.find_by_code(code)
    Profile.find_by_code(code).person
  end
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

我可以合并active范围和find_by_code类方法,例如

User.active.find_by_code("ABC123")

它将找到包含给定代码的配置文件,然后使用该配置文件上的user_id查找关联人员。 AND 它会记住active范围。它是如何做到的?

您可以在生成的查询中看到它首先检索profile,然后查询相关的person

SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`code` = 'ABC123' LIMIT 1
SELECT `user`.* FROM `user` WHERE `user`.`active` = 1 AND `user`.`id` = 8 LIMIT 1

不相关,但我在Rails 3.我知道自那时起finder方法有所改变。

0 个答案:

没有答案