ruby on rails - Filtering by value calculated in instance method -
i have house
model has price
attribute calculated using instance method.
let's price changing due market rates, inflation, etc. need price_today
method current price.
how can create named scope (or something) filter houses using maximum price , minimum price?
i tried doing this, feel it's little hacky...
def index @houses = # houses db if not params[:max_price].nil? @houses.keep_if { |h| h.price_today <= params[:max_price].to_f } end if not params[:min_price].nil? @houses.keep_if { |h| h.price_today >= params[:min_price].to_f } end end
a named scope (or where
clause) faster querying , filtering instantiated objects.
however, i'm afraid if price_today
not exist in db won't able use them.
you can improve code, though.
conditions can made simpler, , can use single call keep_if
.
max = params[:max_price].presence min = params[:min_price].presence if max || min @houses.keep_if |house| = max ? (house.price_today <= max.to_f) : true b = min ? (house.price_today >= min.to_f) : true && b end end
if want, instead of keep_if
can use select
.
Comments
Post a Comment