我有一个 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
最佳答案
这可行:
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
关于ruby-on-rails - rails : model scope filtered by instance method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13884614/