Stef Hej Stef Hej - 1 year ago 76
Ruby Question

ActiveRecord include or join has_one records on where

With following model


# Columns
# job_title :string
# (..)

has_one :spec


# 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 Source


User.where(job_title: "developer").joins(:spec).where(specs: {department: "front-end"})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download