Is it possible to query on virtual attributes?

I have a Person model with attributes first_name and last_name.

I want to implement autocomplete search that looks that the entire
name. Hence I have a method:

def full_name
self.first_name + " " + self.last_name
end

Is it possible for me to query on full_name and have rails match the
first_name and last_name fields?

I currently receive this error when I try, because full_name isn’t an
attribute in the database:

SQLite3::SQLException: no such column: full_name: SELECT
“people”.* FROM “people” WHERE (LOWER(full_name) LIKE ‘he
%’) ORDER BY full_name ASC LIMIT 10

Clay H. wrote:

I have a Person model with attributes first_name and last_name.

I want to implement autocomplete search that looks that the entire
name. Hence I have a method:

def full_name
self.first_name + " " + self.last_name
end

Is it possible for me to query on full_name and have rails match the
first_name and last_name fields?

I currently receive this error when I try, because full_name isn’t an
attribute in the database:

SQLite3::SQLException: no such column: full_name: SELECT
“people”.* FROM “people” WHERE (LOWER(full_name) LIKE ‘he
%’) ORDER BY full_name ASC LIMIT 10

There’s your answer. ActiveRecord find maps directly to database
attributes. You could do something like :conditions => [“first_name
like ‘:name%’ or last_name like ‘:name%’”, {:name => “Smith”}], or
define a computed column in a database view (in which case you will want
the rails_sql_views plugin).

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

In straight SQL you could order on the full name by using SELECT *,
CONCAT(first_name, ’ ', last_name) AS full_name FROM people … ORDER
BY full_name ASC. See if you can work that into a Rails finder syntax.

Walter