I have 2 tables in my app 1. Users, 2. Restaurants. A user can save the names (along with other attributes) of restaurants they've been to. For example user 1 has been to Panda express and Red Robins. These restaurant records also have a "food category" as an attribute of its record. When another user (user 2) lands on user 1's profile page, there's a column that lists the different restaurant food categories for user 1 (ex. American and Chinese).
What I want to be able to do is allow user 2 to click on the food categories to filter and display only restaurants under the category clicked on. (rather than show all restaurants, if user 2 clicks on Chinese, only Panda Express is displayed.)
how do I pass the food category parameter to the restaurants model to filter the results?
--
Users table: user_id | name | email
1 | Bob | bobby@email.com
2 | Alice | alice@email.com
Users restaurants table: users_restaurants_id | food_category | user_id
1 | Chinese | 1
2 | American | 1
Restaurants Table: restaurant_id | name | food_category | user_id
1 | Panda Express | Chinese | 1
2 | Red Robins | American | 1
--
Users Show view
<%= for each @restaurants do |r| %>
<%= link_to r.name, url => { :controller => users, :action => show, :xxx => r.id }
<% end %>
Users controller
def show
@user = User.find(params[:id])
whichfoodcategory => params(:xxx)
unless whichfoodcategory.nil?
#just render all restaurants for all food categories
@restaurants = @user.restaur开发者_如何学Cants
else
#use the params(:xxx) to filter the restaurants model records for @user... but how?
@restaurants = @user.filteredbyfoodcategory
end
end
Restaurants Model
attr_accessor :xxx(?) or :whichfoodcategory(?)
named_scope :filteredbyfoodcategory { select all where user_id = 1 and food_category = :whichfoodcategory? or xxx? }
--
I'm sure I should be using named_scope in the Restaurants model, but I'm not sure how to go about passing the food category to the model.
Here is how you can load all the restaurants with only your existing setup.
@restaurants = @user.restaurants.all(:conditions => ["restaurants.food_category = ?", params[:xxx]])
If you want to change this into named_scopes then perhaps something like this could work:
class Restaurant < ActiveRecord::Base
...
named_scope :by_food_category, lambda { |category| { :conditions => ["restaurants.food_category = ?", category] } }
end
and then in the controller:
@restaurants = @user.restaurants.by_food_category(params[:xxx])
精彩评论