3

我有这样的代码:

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 可能为空,也可能不为空。在类别为空的情况下,我希望该方法简单地传递并返回关系不变。当然, return self 只是返回 Item 类。

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

4

3 回答 3

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

高温高压

于 2013-01-24T12:51:39.597 回答
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不需要上述代码来简单地获取所有项目类别。

于 2013-01-24T12:50:48.663 回答
1

#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
于 2020-06-26T12:46:13.660 回答