如果方法中没有传递参数,则返回对象

时间:2017-11-22 12:02:42

标签: ruby-on-rails

我的模型中有一个类方法,我用作范围

class Foo < ApplicationRecord
   def self.bar(params)
       if !params['some-param'].blank?
           return Foo.where(....)
       elsif !params['another-param'].blank?
           return Foo.where(....)
       end

       self
   end
end

# so in the controller I do something like this
my_var = Foo.bar(params).another_scope.all

工作正常。如果我将代码改为此

def self.bar(params)
   return self if params.empty?

   if !params['some-param'].blank?
       return Foo.where(....)
   end

   if !params['another-param'].blank?
       return Foo.where(....)
   end
end

这会引发错误:undefined method 'another_scope' for nil:NilClass

2 个答案:

答案 0 :(得分:1)

让我们假设params不为空。 params['some-param']params['another-param']都是空的。并且你的方法不会重新编译任何东西。

最好:

def self.bar(params)
    if params['some-param'].present?
        Foo.where(....)
    elsif params['another-param'].present?
        Foo.where(....)
    end

    self
end

答案 1 :(得分:1)

试试这个:

def self.bar(params = {})                 # with a default value
  params.delete_if { |_, v| v.blank? }    # Clean up keys with blank values

  if params['some-param']
    Foo.where(....)
  elsif params['another-param']
    Foo.where(....)
  else                 # if some unknown key present in params OR the params are blank
    self
  end
end