【发布时间】:2010-12-16 10:04:02
【问题描述】:
我的应用中有 2 张桌子 1. 用户,2. 餐厅。用户可以保存他们去过的餐馆的名称(连同其他属性)。例如,用户 1 去过 Panda express 和 Red Robins。这些餐馆记录还具有“食物类别”作为其记录的属性。当另一个用户(用户 2)登陆用户 1 的个人资料页面时,会有一个列列出用户 1 的不同餐厅食物类别(例如美国和中国)。
我想要做的是允许用户 2 点击食物类别来过滤并仅显示点击类别下的餐厅。 (而不是显示所有餐厅,如果用户2点击中文,则只显示熊猫快餐。)
如何将食物类别参数传递给餐馆模型以过滤结果?
--
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? }
--
我确定我应该在餐厅模型中使用 named_scope,但我不确定如何将食物类别传递给模型。
【问题讨论】:
标签: ruby-on-rails lambda filtering parameter-passing named-scope