In the Rails model, I am trying to get named_scope, which filters start_date and end_date. It is easy. But I will have to do this in many different areas many times.
Is it asking for trouble? If so, why (SQL injection?) And there is another way to achieve this.
named_scope :between, lambda {|start_date, end_date, field|
{ :conditions => ["#{field} >= ? AND #{field} <= ?", start_date, end_date] }
}
EDIT: Solution Used
Using the Eggdrop line of thinking, I went with:
@@valid_fields = %w(fields in here)
named_scope :between, lambda{ |start_date, end_date, field_name|
field = (@@valid_fields.include?(field_name)) ? (field_name) : raise (ActiveRecord::StatementInvalid)
{ :conditions => ["#{field} >= ? AND #{field} <= ?", start_date, end_date]}
}
Now I can reuse my named_scope for fields that I want to filter in a date range, without rewriting essentially the same scope again and again, and also for whitelisting field names to avoid any problems with column names and complex SQL injection if the code has ever received user input in the future.