ruby on rails - Handling multiple filters (params) cleanly in controller -
i have class called post, , need able accommodate following scenarios:
- if user selects category, show posts category
- if user selects type, show posts type
- if user selects category , type, show posts category type
- if user selects nothing, show posts
i'm wondering if it's inevitable controller going gross ton of conditionals... here's flawed approach @ tackling – know how can accomplish this?
class postscontroller < applicationcontroller def index @user = current_user # if user has not specified type or category, # show them @posts = post.all # if user has selected category, no type, # show posts category. if params[:category] && !params[:type] category = category.find(params[:category]) @posts = @category.posts end # if user has selected category , type, show # posts category type if params[:category] && params[:type] category = category.find(params[:category]) type = params[:type] @posts = category.posts.where(post_type: type) end # if user has selected type not category, show # of posts type if params[:type] && !params[:category] type = params[:type] @posts = post.where(post_type: post_type) end end end
you'll better off following convention of "fat models, skinny controllers", meaning should put kind of logic in model itself. post
class should able report posts correspond conditions, can define method that:
class post < activerecord::base ... def self.by_category_and_type(category = nil, type = nil) return where(category: category, type: type) if category && type return where(category: category) if category return where(type: type) if type end ... end
then in controller can call
@posts = post.by_category_and_type(params[:category], params[:type])
i haven't tested this, think should trick. let me know if doesn't!
Comments
Post a Comment