Suppose, I have models Article and Category with HABTM relation. I can have different categories with names like mobile, desktop etc. I need list view for each category. For example /mobile path give me all Articles belongs to Category mobile, /desktop path give me all Articles belongs to category desktop and /articles path give me totally all Articles. What is the best way to organize it (controllers, views, routes)? For each category create controller? But it's not DRY...and categories may be added by user later...
2 に答える
1
ルート:
get 'category/:type' => 'categories#index'
コントローラ:
def index
type = params[:type]
## fetch categories based on type
categories = Category.where(type: type)
end
ここで確認する必要がある基本的なことは、ルートです。任意の数のカテゴリ タイプで機能するルートを 1 つだけ追加します
于 2013-11-06T13:08:00.113 に答える
1
追加のコントローラーを作成する必要はありません。
class ArticlesController
def index
@articles = case params[:type]
when 'mobile'
# .. select mobile articles
when 'desktop'
# .. select desktop articles
else
Article.all
end
# ...
end
end
次にroutes.rb
match "/mobile", controller: :articles, action: :index, type: 'mobile'
match "/desktop", controller: :articles, action: :index, type: 'desktop'
resources :articles
于 2013-11-06T13:04:41.467 に答える