0

私のアプリには2つのテーブルがあります。1ユーザー、2レストラン。ユーザーは、彼らが行ったレストランの名前(他の属性とともに)を保存することができます。たとえば、ユーザー1はPanda expressとRed Robinsに行っています。これらのレストランのレコードには、そのレコードの属性として「食品カテゴリ」もあります。別のユーザー(ユーザー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を使用する必要があります確信しているが、私はどのようにわからないんだけどモデルに食べ物のカテゴリを渡すようになります。

答えて

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])