Topic: Find * WHERE first-letter = ?

Is this possible? Would it need to be a find_by_sql string?

Re: Find * WHERE first-letter = ?

class Post < ActiveRecord::Base
  validates_presence_of :title

  def self.find_by_first_letter(letter)
    find(:all, :conditions => ['title LIKE ?', "#{letter}%"], :order => 'title ASC')
  end

end

vinnie - rails forum admin

Re: Find * WHERE first-letter = ?

I get nothing when trying that... Finds nothing, when there is something to find.

The SQL in the log:

SELECT * FROM contacts WHERE (name LIKE 'T%') ORDER BY name ASC

Tried with an extra % on the left side to, but nothing there either.

4

Re: Find * WHERE first-letter = ?

That SQL statement should work fine. I'd double check your database to make sure you have data that it will return. I just ran it against a table of states:

mysql> select * from states where (name LIKE 'T%') order by name ASC;
+----+-----------+------+------------+
| id | name      | abbr | country_id |
+----+-----------+------+------------+
| 42 | Tennessee | TN   |          1 |
| 43 | Texas     | TX   |          1 |
+----+-----------+------+------------+
2 rows in set (0.00 sec)

Re: Find * WHERE first-letter = ?

Yeah, I tested it to, and it worked on the db I'm using. Something wrong with my controller code then... I have this:

$result = Contact.find_by_first_letter(params[:letter])

Edit: Oh, never mind.. got PHP on my mind, used a $ instead of an @...

Last edited by Hans Nilsson (2006-11-12 08:45:50)

Re: Find * WHERE first-letter = ?

My code was missing a closing square bracket. Oops sad

I edited it, try the new method.

vinnie - rails forum admin

Re: Find * WHERE first-letter = ?

Yeah, I found it Vin. Thanks!