ruby-on-rails - rails : model scope filtered by instance method

标签 ruby-on-rails

我有一个 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/

相关文章:

ruby-on-rails - 如何卸载/删除旧的 ruby​​ 版本并保持更新。我安装了两个版本的 ruby

ruby-on-rails - 在 Rails 中的资源管道中渲染部分

ruby-on-rails - ActiveModelSerializer 0.10.0中的URL助手?

mysql - 针对日期字段查询日期时间字段的最佳方法是什么?

ruby-on-rails - rails : create Parent, 如果不存在,同时创建子记录

ruby-on-rails - ruby 中相同对象值的不同哈希值

ruby-on-rails - compass Sprite 生成器有什么好的替代品吗? (滚动 Sprite 生成器)

ruby-on-rails - 如何修复 "uninitialized constant User"

ruby-on-rails - 从旧版 ruby​​/rbenv 迁移的问题

ruby-on-rails - 启动我的 Rails 服务器时出错 : Circular dependency detected while autoloading constant AdminUser (RuntimeError)