[英]Finding all records containing a specific attribute in rails
I have 2 tables in my app 1. Users, 2. Restaurants. 我的应用程序中有2个表。1.用户,2.餐馆。 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.
例如,用户1曾经去过Panda Express和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).
当另一个用户(用户2)登陆用户1的个人资料页面时,会出现一列,列出用户1的不同餐厅食物类别(例如美国和中国)。
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. 我想要做的是允许用户2单击食物类别以过滤并仅显示所单击类别下的餐馆。 (rather than show all restaurants, if user 2 clicks on Chinese, only Panda Express is displayed.)
(如果用户2单击中文,则不显示所有餐厅,而仅显示Panda Express。)
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.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? }
-- -
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. 我确定我应该在Restaurantss模型中使用named_scope,但是我不确定如何将食物类别传递给模型。
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: 如果您想将其更改为named_scopes,那么也许可以使用以下方法:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.