ActiveRecord包含或加入has_one记录在哪里

时间:2016-07-22 21:01:39

标签: ruby-on-rails ruby activerecord

使用以下型号

user.rb

# Columns
# job_title :string
#  (..)

has_one :spec

spec.rb

# Columns
# org_unit :string
# department :string
# room_number :string

belongs_to :user

..我能写:

irb(main):005:0> user.spec.department
  Spec Load (0.0ms)  SELECT  "specs".* FROM "specs" WHERE "specs"."user_id" = ?
    LIMIT ?  [["user_id", 1], ["LIMIT", 1]]
=> front-end

但现在我想对两个类进行搜索,如:

User.where(job_title: "developer").where(self.spec.department: "front-end")

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:3)

尝试:

User.where(job_title: "developer").joins(:spec).where(specs: {department: "front-end"})