2

I have a User controller and method named 'index' for listing users. And in view there is a filtering option (with status pending, active, deleted). I wrote the code and its working fine. But I need to know the code that I wrote is correct or not, or is any easy method to code. Is that correct method for validating status in controller(validating if the query string status include in a set of statuses). Please help

I used following code:

class UsersController < ApplicationController
  def index
     @filter_field = ''
     if ((not params[:status].nil?) && ['pending', 'active', 'deleted'].include?(params[:status]))
      @filter_field = params[:status]
    end
    @users      = User.select_all(@filter_field)
  end
end

class User < ActiveRecord::Base 
  def self.select_all filter
    if filter.empty?    
      User.find(:all)
    else
      User.find(:all, :conditions => ['status = ?', filter]))      
    end
  end
end
4

1 回答 1

1

你可以这样做:

def index
  filter = %w(pending active deleted).include?(params[:status]) ? params[:status] : ''
  @users = User.select_all(filter)
end

它使检查更容易理解+不需要实例变量对吗?

顺便说一句,我觉得:

['pending', 'active', 'deleted']

应该由一个方法给出,避免一个魔法数组

于 2013-09-06T08:31:22.310 回答