开发者

Trying to perform a method on a params in Rails

I want to write a method that loops through all the params to make sure they aren't all blank.

My params are:

params[:search][:company]
params[:search][:phone]
params[:search][:city]
params[:search][:state]
params[:search][:email]

I have this method:

def all_blank_check(params)
  array=[]

  params[:search].each do |key, value|
    array << value unless value.blank?
  end

  if array.count < 1
      return true
  else
     return false
  end
end

But when I try something like all_blank_check(params) I get the following error:

NoMethodError (undefined method `all_blank_check' for #<Class:0x108c08830>):

Do I need to convert the params to an array first? Can't I perform a method on params?

Edit - full source:

        def index
          @customers = Customer.search_search(params)
        end

def self.search_search(params) search_field = [] search_values = [] array = [] test = '' if !params[:search].nil? && all_blank_check(params[:search] if !params[:search].nil? && !params[:search][:company].blank? search_field << 'customers.company LIKE ?' search_values << "%#{params[:search][:company]}%" end if !params[:search].nil? && !params[:search][:city].blank? search_field << 'customers.city = ?' search_values << "#{params[:search][:city]}" end if !params[:search].nil? && !params[:search][:phone].blank? sea开发者_Go百科rch_field << 'customers.phone_1 = ?' search_values << "%#{params[:search][:phone]}%" end conditions = [search_field.join(' AND ')] + search_values Customer.where(conditions).includes(:customer_contacts).limit(10) end end def all_blank_check(params) params[:search].each do |key, value| array << value unless value.blank? end if array.count < 1 return false end if array.count > 1 return true end end


You can also use more Ruby-minded code like this:

def self.all_blank?(params)
   params[:search].count{|key, value| !value.blank?} == 0
end

This counts the values that are not blank; if the number is 0, it means all are blank. It avoids creating a new array just for counting.


The problem is not the type of params, the problem is that the method all_blank_check does not exist on the object you call it on.

You defined it as an instance method and you're trying to call it from the class method search_param, which won't work.

If you want to make all_blank_check a class method you need to change the definition to def self.all_blank_check(params) - same as search_param.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜