简体   繁体   English

优雅的 ruby function,需要帮助清理它,所以它看起来像 ruby

[英]Elegant ruby function, need help cleaning this up so it looks like ruby

I have to parameters: name and age我必须参数:姓名和年龄

def self.search(name, age)

end

If name is not empty/nil, then add it to the search expression.如果 name 不为空/nil,则将其添加到搜索表达式中。

If age is not empty/nil, then add it to the search expression.如果年龄不为空/nil,则将其添加到搜索表达式中。

if both are nil, return all.如果两者都为零,则全部返回。

So far I have:到目前为止,我有:

def self.search(name, age)

   if name.nil? && age.nil?
      return User.all
   end



end

Finding it hard to write this in a elegant way.很难以优雅的方式编写此代码。

def self.search(name, age)
  conditions = {}
  conditions[:name] = name if name
  conditions[:age] = age if age
  User.find(:all, :conditions => conditions)
end

I'm not sure what sort of search you're doing but I prefer to handle these sort of things in a scope.我不确定你在做什么类型的搜索,但我更喜欢在 scope 中处理这些事情。

class User < ActiveRecord::Base
  scope :by_name, lamba{|name| name.nil?? scoped : where(:name=>name) }
  scope :by_age, lamba{|age| age.nil?? scoped : where(:age=>age) }

  def self.search(name, age)
    User.by_name(name).by_age(age)
  end
end

It's a bit more code overall I suppose but it's more reusable and everything is in it's place.我想它总体上要多一点代码,但它更可重用,而且一切都在它的位置。

In Rails 3 you can do it like this:在 Rails 3 中,您可以这样做:

def self.search(name, age)
  scope = User
  scope.where(:name => name) if name.present?
  scope.where(:age => age) if age.present?
  scope
end

Note the use of present?注意现在的用法? rather than nil?而不是零? to skip empty strings as well as nil.跳过空字符串以及 nil。

In the other comment you mentioned wanting to OR these conditions.在您提到的另一条评论中,想要或这些条件。 ActiveRecord does not provide convenient facilities for that; ActiveRecord 没有为此提供便利的设施; all conditions are AND by default.默认情况下,所有条件都是 AND。 You will need to construct your own conditions like so:您将需要像这样构建自己的条件:

def self.search(name, age)
  scope = User
  if name.present? && age.present?
    scope.where('name = ? OR age = ?', name, age)
  else
    scope.where(:name => name) if name.present?
    scope.where(:age => age) if age.present?
  end
  scope
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM