3

我有一个 Cover 模型,在cover.rb文件中,我还定义了一个名为的方法,该方法size返回一个表示“小、中、大”的整数。我的问题是如何检索所有小/中/大封面?我的猜测是使用scope,但我不知道如何将size方法作为条件传递。

class Cover < ActiveRecord::Base
  attr_accessible :length, :width

  # TODO
  scope :small
  scope :intermediate
  scope :large

  # I have simplified the method for clarity.
  # 0 - small; 1 - intermediate;  2 - large
  def size
    std_length = std_width = 15
    if length < std_length && width < std_width
      0
    elsif length > std_length && width > std_width
      2
    else
      1
    end
  end

end
4

3 回答 3

4

这可以工作:

class Cover < ActiveRecord::Base
  attr_accessible :length, :width

  scope :of_size, lambda{ |size| 
                          case size
                            when :small
                              where('width < 15 AND height < 15')
                            when :large
                              where('width > 15 AND height > 15')
                            when :intermediate
                              where('(width < 15 AND height > 15) OR (width > 15 AND height < 15)')
                            else
                              where(id: -1) # workaround to return empty AR::Relation
                        }

  def size
    std_length = std_width = 15
    return :small if length < std_length && width < std_width
    return :large if length > std_length && width > std_width
    return :intermediate
  end

end

并像这样使用它:

Cover.of_size(:small) # => returns an array of Cover with size == small

为了使它与几个参数一起工作:

# in the model:
scope :of_size, lambda{ |*size| all.select{ |cover| [size].flatten.include?(cover.size) } }
# how to call it:
Cover.of_size(:small, :large) # returns an array of covers with Large OR Small size
于 2012-12-14T18:55:33.080 回答
0

我认为您最简单的解决方案是类方法:

def self.small
  Cover.all.select {|c| c.size == 0}
end
于 2012-12-14T18:57:39.200 回答
0

如果您正在考虑传递三种尺寸之一,您不妨调用三种范围之一。它会更具可读性。

scope :small, where('width < 15 AND height < 15')
scope :large, where('width > 15 AND height > 15')
scope :intermediate, where('(width < 15 AND height > 15) OR (width > 15 AND height < 15)')
于 2013-05-22T23:08:22.910 回答