Wednesday 15 January 2014

sql - Chaining scopes with joins -



sql - Chaining scopes with joins -

these 2 scopes don't seem chainable

scope :approved, ->{ with_stage(:approved)}

which in sql is

where (pages.stage & 4 <> 0)

and

scope :with_galleries, ->{ joins("left outer bring together galleries on galleries.galleriable_type = 'brand' , galleries.galleriable_id = page.brand_id").where("galleries.id not null") }

this scope should give pages have galleries (each page has 1 brand , each brand can have many galleries)

if chain :with_galleries, seems rest of conditions on pages table lost

am doing joins wrong?

you more useful result if allow activerecord more of heavy lifting you. in particular, if you've set associations properly, should able write next instead:

scope :with_galleries, joins(brand: :galleries)

... yield chainable scope.

that depend on 2 associations, 1 page model brand:

'belongs_to :brand'

and 1 brand galleries::

has_many :galleries, as: :galleriable

i'm inferring model setup query you've written, may have guessed wrong. basic principle here declare associations , allow activerecord build queries (unless query unusual, yours not -- you're filtering depending on whether there associated records, mutual operation).

sql ruby-on-rails ruby-on-rails-4 outer-join

No comments:

Post a Comment