如何从类方法返回未更改的AR关系

时间:2013-01-24 12:45:43

标签: ruby-on-rails

我有这样的代码:

class Item < ActiveRecord::Base
  class << self
    def for_category(c)
      if c
        return where(:category_id => c.id)
      else
        return self
      end
    end
  end
end

我需要这样称呼它:

Item.where("created_at > ?", Time.now - 1.week).for_category(@category)

@category可能是也可能不是null。在category为null的情况下,我希望方法简单地传递并返回不变的关系。当然,return self只返回Item类。

这样做的正确方法是什么?

3 个答案:

答案 0 :(得分:4)

您是否正在尝试返回范围(而不是类本身)以进一步执行范围操作?如果是这样,那么类似下面的内容应该有效:

class Item < ActiveRecord::Base
  class << self
    def for_category(c)
      if c
        return where(:category_id => c.id)
      else
        return scoped
      end
    end
  end
end

HTH

答案 1 :(得分:1)

class Item < ActiveRecord::Base
    def self.for_category(c)
      conditions = {:category_id => c.id}
      conditions.delete_if {|key,val| val.blank? }
      self.where(conditions)
    end
end

您的类别相关联?如果是,那么您只需按Item.where("created_at > ?", Time.now - 1.week).categroies获取上述代码所需的所有项目类别。

答案 2 :(得分:0)

#scoped在Rails 4中已被弃用。您可以使用#all来达到相同的效果:

class Item < ActiveRecord::Base
  class << self
    def for_category(c)
      if c
        return where(:category_id => c.id)
      else
        return all
      end
    end
  end
end
相关问题