jeudi 24 décembre 2015

Rails where clause with a logic

I have a table where I am storing age ranges.

The age range is saved as Range object e.g. (1..4) in ruby. Now when I have to fetch all the records where one age falls in the age range. I have to do this

table.select{|s| s.age_range.include?(19)}

but this returns an array , not an active record relation object. So I would prefer doing something like:

table.where(s.age_range:  age_range.include?(19)}

which is obviously not correct. But its gets the point across. I would like to know if this is possible .

model.rb

class Model < ActiveRecord::Base
  attr_accessor :age_range_min, :age_range_max

  before_create :set_age_range
  serialize :age_range

  def set_age_range
    self.age_range = (age_range_min.to_i..age_range_max.to_i)
  end
end

Aucun commentaire:

Enregistrer un commentaire