Created
February 10, 2014 11:20
-
-
Save zmajstor/8914214 to your computer and use it in GitHub Desktop.
AR DRY scoping of the nested models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Našao! :)
scope :launched, joins(:collection).merge(Collection.live)
eh, činilo mi se da mora bit tako nešto ... thx, častim kavom u subotu :)
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
Hmm... mislim da bi ovo moglo biti dobro:
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.