我的应用程序中有2个表1.用户,2。餐馆。用户可以保存他们去过的餐馆的名称(以及其他属性)。例如,用户1去过Panda express和Red Robins。这些餐馆记录还有一个“食品类别”作为其记录的属性。当另一个用户(用户2)登陆用户1的简档页面时,有一列列出了用户1的不同餐馆食物类别(例如美国和中国)。
我希望能够做的是允许用户2点击食物类别来过滤并仅显示点击类别下的餐馆。 (而不是显示所有餐厅,如果用户2点击中文,则只显示Panda Express。)
如何将食品类别参数传递给餐馆模型以过滤结果?
-
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.restaurants
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? }
-
我确定我应该在Restaurants模型中使用named_scope,但我不确定如何将食物类别传递给模型。
答案 0 :(得分:1)
以下是仅使用现有设置加载所有餐厅的方法。
@restaurants = @user.restaurants.all(:conditions => ["restaurants.food_category = ?", params[:xxx]])
如果你想将它改成named_scopes,那么这样的事情可能会起作用:
class Restaurant < ActiveRecord::Base
...
named_scope :by_food_category, lambda { |category| { :conditions => ["restaurants.food_category = ?", category] } }
end
然后在控制器中:
@restaurants = @user.restaurants.by_food_category(params[:xxx])