ActiveRecordã§ãã©ã¡ã¼ã¿ã§conditionsæ¡ä»¶ã追å ãããããã«ã
ä¼ç¤¾ã®ããã¸ã§ã¯ãã§ä½¿ããã¦ããActiveRecordã®é¢æ°ãç´¹ä»ã
lib/active_record/active_record_helper.rb
module ActiveRecordHelper def flatten_conditions(conditions, op = "and") return nil if conditions.empty? ps = [] condition = conditions.collect do |c| next if c.size < 1 ps += c[1..(c.size)] "( #{c[0]} )" end.delete_if { |c| c.blank? }.join(" #{op} ") [condition, ps].flatten unless condition.empty? end end class ActiveRecord::Base include ActiveRecordHelper end
ããã§ãparams[]ã®å¤ã«ãã£ã¦conditionã«æ¡ä»¶ãå ãããå ããªãã£ããããããã°ã©ã ã®æã
ç°¡åã«æ¡ä»¶ãä½ãäºãã§ãã¾ãã
@condition = [] @condition << [" prefecture_id = ? ", params[:prefecture] ] if params[:prefecture] @condition << [" sex = ? ", params[:sex] ] if params[:sex] @users = User.find(:all, :conditions => @conidition)
è¤æ°æ¡ä»¶ãæ¸ãæé¢åãªãã§ãå©ãã£ã¦ãã¾ãã
ãã©ã¡ã¼ã¿ãç¡ãã@conditions = [] ã®ã¿ã®å ´åã§ããã°ãnilãè¿ã£ã¦æ¡ä»¶ç¡ããªãã®ã§ã