我有一個名爲Post類,我需要能夠適應以下情況:如果用戶選擇一個類別處理多個過濾器(PARAMS)乾淨利落地控制
- ,只顯示從該類別的職位
- 如果用戶選擇一個類型,只顯示與該類型
- 帖子如果用戶選擇一個類別,類型,只顯示從該類別的職位與該類型
- 如果用戶選擇了什麼,顯示所有帖子
我想知道,如果它是不可避免的,我的控制器只是去看看毛一噸的條件句...這裏是我在處理這一缺陷的方法 - 沒有人知道我能做到這一點?
class PostsController < ApplicationController
def index
@user = current_user
# If a user has not specified a type or category,
# show them everything
@posts = Post.all
# If a user has selected a category, but no type, only
# show posts from that category.
if params[:category] && !params[:type]
category = Category.find(params[:category])
@posts = @category.posts
end
# If a user has selected a category and a type, only show
# posts from that category with that type
if params[:category] && params[:type]
category = Category.find(params[:category])
type = params[:type]
@posts = category.posts.where(post_type: type)
end
# If a user has selected a type but not a category, show all
# of the posts with that type
if params[:type] && !params[:category]
type = params[:type]
@posts = Post.where(post_type: post_type)
end
end
end
Cheezus!這絕對是我們應該使用的模式。 – goo