【问题标题】:Finding all records containing a specific attribute in rails在rails中查找包含特定属性的所有记录
【发布时间】: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


    【解决方案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])
    

    【讨论】:

      猜你喜欢
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2021-06-18
      • 2016-02-19
      • 2013-03-19
      相关资源
      最近更新 更多