0

I am using Rails 3.1.0

I have two models, A and B. A has_one B, but B can be null. B belongs_to A. B has a boolean field called "visible."

I want to get all A records that have a non-null B and a B with "visible" set to true.

What is a concise and efficient way of doing this query?

What I've done so far:

I created a scope that gets the A's with non-null B's (I think).

scope :has_b, includes(:b).where(B.arel_table[:id].not_eq(nil))

Is there a way to chain the visible == true condition to this scope?

mushroom
  • 6,201
  • 5
  • 36
  • 63

2 Answers2

2
A.includes(:bs).where(:bs => { :visible => true })

Zach Kemp was almost right

So, in scope:

scope as_with_visible_bs includes(:bs)
  .where(B.arel_table[:id].not_eq(nil))
  .where(:bs => { :visible => true })
antiqe
  • 1,125
  • 8
  • 17
0

Have a look at the 'joins' section here. This query should do what you need:

A.joins(:bs).where(:bs => { :visible => true })
Zach Kemp
  • 11,736
  • 1
  • 32
  • 46