查找包含轨道中特定属性的所有记录
问题描述:
我的应用程序中有2个表格1. Users,2. Restaurants。用户可以保存他们去过的餐厅的名字(以及其他属性)。例如用户1曾去过熊猫快车和红罗宾斯。这些餐厅记录还有一个“食品类别”作为其记录的属性。当另一个用户(用户2)登录用户1的个人资料页面时,有一列列出用户1的不同餐馆食物类别(例如美国和中国)。查找包含轨道中特定属性的所有记录
我想要做的是允许用户2点击食品类别来过滤和显示仅点击类别下的餐馆。 (而不是显示所有餐馆,如果用户2点击中文,则只显示熊猫快递。)
如何将食品类别参数传递给餐馆模型以过滤结果?
-
Users table: user_id | name | email
1 | Bob | [email protected]
2 | Alice | [email protected]
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,但我不知道如何开始将食品类别传递给模型。
答
以下是如何使用现有设置加载所有餐厅。
@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])