0

I have a model X with an attribute thedate of type datetime.

What is the slickest way to make thedate's year available for dynamic finders?

Examples:

X.find_by_year(2012)
X.find_by_location_and_year('here', 2012)
X.find_by_year_and_name(2012, 'name')
X.find_all_by_year(2012)
...

So far I found this custom finder approach, but apparently that would require to implement each and every desired method manually. I want to avoid that.

Community
  • 1
  • 1
user569825
  • 2,369
  • 1
  • 25
  • 45

1 Answers1

0

The best say is do a scope instead of trying using dynamic find. You can create the scope year and scope and use it

scope :year, lambda { |year| { ['thedate > ? AND thedate < ?', DateTime.now.change(:year => year).beginning_of_year, DateTime.now.change(:year => year).ending_of_year] }

You can use by X.year(2012)

shingara
  • 46,608
  • 11
  • 99
  • 105
  • With that approach I guess I'll need to implement any necessary combinations (e.g. year & name) manually. Right? It's probably a good option still. – user569825 Mar 21 '12 at 11:19