Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: model scope filtered by instance method

I have a Cover model, in the cover.rb file, I also define a method called size which returns an integer representing 'small, intermediate, large'. My question is how can I retrieve all the small/intermediate/large covers? My guess is to use scope, but I cannot figure out how to pass the size method as a condition.

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
like image 888
Chelsea White Avatar asked Jul 09 '26 03:07

Chelsea White


1 Answers

This could work:

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

And use it like this:

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

To make it work with several arguments:

# 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
like image 191
MrYoshiji Avatar answered Jul 11 '26 19:07

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!