rails适用于if变量不为零的情况,否则应用全部 - 更好的方式

时间:2013-09-13 09:30:46

标签: ruby-on-rails activerecord where-clause

如何优化/重构此rails代码,

如果co不是零,我想在国家和城市适用条件,如果没有,则适用全部。

  def pre(co = nil,ci = nil)

    cond1 =  co.nil? ? "all" : "where(:id => co)"
    cond2 =  ci.nil? ? "all" : "where(:id => ci)"

    @countries = Country.send(cond1).order(:name).map{|i| [i.name,i.id]}  
    @cities = City.send(cond2).order(:name).map{|i| [i.name,i.id]}  

  end

这是一种不错的方式还是有更好的方式?

3 个答案:

答案 0 :(得分:1)

@countries = Country.where(co.nil? || {:id => co}).order(:name).map{|i| [i.name,i.id]}  
@cities = City.where(ci.nil? || {:id => ci}).order(:name).map{|i| [i.name,i.id]} 

答案 1 :(得分:0)

您可以尝试这样的事情

@country = Country
@city = City

if co.blank?
@country = @country.where(:id => co)
end

if ci.blank?
@city = @city.where(:id => ci)
end

@countries = @country.order(:name).all.map{|i| [i.name,i.id]}  
@cities = @city.order(:name).all.map{|i| [i.name,i.id]}  

答案 2 :(得分:0)

你会想到这样的事情。

def pre(co = nil, ci = nil)
  @countries = scopify(Country, co)
  @cities    = scopify(City, ci)
end

def scopify(model_or_scope, attribute)
  scope = model_or_scope.scoped
  scope = scope.where(:id => attribute) if attribute.present?
  scope.order(:name).map { |s| [s.name, s.id] }
end