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.
Metawhere (now Squeel) extends ActiveRecord's implementation of Arel which is a SQL generator. That means it will turn some statement in SQL eg:
@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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.