views:

36

answers:

1

Hello,

I am developing a small user application in Rails 3 and is stuck on a search feature. I got a table called Profile which holds Firstname and Lastname. When searching this table I use:

Profile.find_all_by_firstname(params[:keyword])

The thing is that I want the user to be able to search a table that holds contacts (profile_id and friend_id only) but I want them to be able to seach by name here too. How is this done?

For example:

John searches for the name Ann which is a contact of his. Since the Contact table does not store names the search must include the Profile table in the query. How can I do this?

UPDATE

This join query fetches everyone not only the contacts, can anyone spot a problem with it?

Profile.find_all_by_firstname(params[:keyword],
:select => "firstname, lastname, user_id",
:joins => "left outer join contacts on profiles.id = contacts.profile_id")
+1  A: 
Profile.find_all_by_firstname(params[:keyword],
:select => "firstname, lastname, user_id",
:joins => "left outer join contacts on profiles.id = contacts.profile_id")

this query fetches everyone because you serch only by the firstname If you whant select contacts that are friends of the particular user firstly you must have his id Then you should add this to your conditions

current_user = Profile.first 
Profile.find(:all, 
             :conditions => ["profiles.firstname = ? AND contacts.friend_id = ?", params[:keyword], current_user.id],
             :joins => :contacts)

or make join conditional

current_user = Profile.first 
Profile.find_all_by_firstname(params[:keyword],
:select => "firstname, lastname, user_id",
:joins => "INNER JOIN contacts on (profiles.id = contacts.profile_id AND contacts.friend_id = #{current_user.id})")

but I'm not quite sure about syntax

Bohdan Pohorilets
This works but I cannot include the params(:keyword) in the WHERE statment without getting errors: @profiles = Profile.find_by_sql("SELECT * FROM contacts INNER JOIN profiles ON contacts.friend_id = profiles.id WHERE profiles.firstname = keyword")
Jonathan Clark
If this is your exact code then you should change it to @profiles = Profile.find_by_sql("SELECT * FROM contacts INNER JOIN profiles ON contacts.friend_id = profiles.id WHERE profiles.firstname = #{params[:keyword]}")
Bohdan Pohorilets