Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Created February 10, 2014 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmajstor/8914214 to your computer and use it in GitHub Desktop.
Save zmajstor/8914214 to your computer and use it in GitHub Desktop.
AR DRY scoping of the nested models
class Collection < ActiveRecord::Base
has_many :products
scope :live, where("collections.end_date IS NOT NULL AND collections.end_date >= ?", Time.now.to_date)
end
class Product < ActiveRecord::Base
belongs_to :collection
# how to DRY this .where ?
scope :launched, joins(:collection).where("collections.end_date IS NOT NULL AND collections.end_date >= ?", Time.now.to_date)
end
# usage:
Product.launched
# Product scope which belongs_to Collection.live
@janko
Copy link

janko commented Feb 10, 2014

Hmm... mislim da bi ovo moglo biti dobro:

class Product < ActiveRecord::Base
  belongs_to :collection

  scope :launched, joins(:collection).where(collections: {id: Collection.live.pluck(:id)})
end

Btw, znaš da trebaš koristiti lambde za scopeove? Pogotovo jer koristiš Time.now, on će ti se evaluateati samo jednom kad ti se klasa loada.

@janko
Copy link

janko commented Feb 10, 2014

Našao! :)

scope :launched, joins(:collection).merge(Collection.live)

@zmajstor
Copy link
Author

eh, činilo mi se da mora bit tako nešto ... thx, častim kavom u subotu :)

@zmajstor
Copy link
Author

da, znam za lambda, ali, naravno da smetnem s uma kad najviše treba ... :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment