AR association question

Hi there,

I have a favorites table in my DB that has a user_id and restaurant_id columns.

In my restaurant controller I have a user ID and need to get all the restaurants that the user has marked as favorites. I would like to do something similiar to:

@results = Favorite.find_all_by_user_id(current_user.id)

This however returns a list of "favorites" not "restaurants". What is the best way to get the list of restaurants?

Thanks, steve

@results = User.find(current_user.id).restaurants

That will work if you have the habtm relationships set up correctly

Or if you don't:

@results = Restaurant.find_all_by_id(Favorite.find_all_by_user_id(current_user.id).map {|x| x.restaurant_id})

Thanks for the help. The first suggestion didn't work - the second one did however. I have the habtm relationships set up as follows:

class Favorite < ActiveRecord::Base   belongs_to :restaurant   belongs_to :user

class User < ActiveRecord::Base   has_many :favorites, :dependent => :destroy

class Restaurant < ActiveRecord::Base   has_many :favorites , :dependent => :destroy

Any ideas why the first solution doesn't work?(it says there is not such method "Restaurants")

Thanks, steve

ESPNDev@gmail.com wrote:

Thanks for the help. The first suggestion didn't work - the second one did however. I have the habtm relationships set up as follows:

You don't have any hatbm relation ships.

Add has_many :restaurants, :through => :favourites to User and you
will be able to do things like User.find(...).restaurants.

Fred