Has anyone been able to find a way to search a calculated field using metawhere or metasearch in rails 3? I can search any field but calculated fields. There has to be a way. For anyone not familiar with metasearch or metawhere here is a railscast.
http://railscasts.com/episodes/251-metawhere-metasearch
Metawhere (now Squeel) extends ActiveRecord's implementation of Arel which is a SQL generator. That means it will turn some statement in SQL e.g :
@user.order("birthday").to_sql #=> SELECT users.* FROM users ORDER BY birthday
When you do User.find(:all).sort_by(&:age)
you are working on a the result of find(:all), an Array, and the sorting is done in Ruby with Enumerable which is slower and has nothing to do with the database.
So no, you cannot use Metawhere on
def age
date.today - birthday
end
unless you store the result in the database.
However you can use the SQL statements like COUNT AVG MAX etc with GROUP and HAVING to do calculation directly on the database.
User.select("users.*, COUNT(user_id) AS vote_num").joins(:votes).group("user_id")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With