Stef Hej Stef Hej - 4 months ago 17
Ruby Question

ActiveRecord include or join has_one records on where

With following model

user.rb

# Columns
# job_title :string
# (..)

has_one :spec


spec.rb

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

belongs_to :user


.. I'm able to write:

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


But now I'd like to do a search on both classes like:

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


Is there any way to do that?

Answer

Try:

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