Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Searching calculated fields using metasearch and metawhere

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

like image 214
user893447 Avatar asked Nov 14 '22 18:11

user893447


1 Answers

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")

like image 114
charlysisto Avatar answered Dec 20 '22 01:12

charlysisto