Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Range data-type in Rails model creation?

Am using Rails version 3. I want to create a model , in which i have a field called "Page-visits" I want it to hold range as value, eg: (50 .. 100) , (1000 .. 5000) etc. How to achieve this ?? Even if there is no such data-type at present in rails, I would like to know other ways of how to achieve this ?

like image 942
Hemanth Avatar asked Oct 17 '25 03:10

Hemanth


1 Answers

I'm assuming that you actually want to store a range in your model, and not a value within a range. (If you wanted to do the latter, validations would be your answer).

So, range. In a model. You've got two options, each of which are pretty decent.

Option 1: Create a column (range_column) with type 'text'. Pass a Ruby range object to the column, like @my_model_object.range_column = (50..100). Tell Rails to serialize your range like this:

class MyModel < ActiveRecord::Base
  serialize :range_column
end

Now, Rails will automatically convert your range to YAML for database storage, and convert it back to the range object when it retrieves the record again. Doesn't get much easier than that!

Option 2: Create two columns (range_start and range_end) with type 'integer'. Set up something in your model like this:

class MyModel < ActiveRecord::Base
  def range=(rstart, rend)
    self.range_start = rstart
    self.range_end   = rend
  end

  def range
    (range_start..range_end) # or as an array, or however you want to return it
  end
end

The first option is easier (and, in my opinion, better), while the second gives you a tad bit more flexibility out of the box in case you don't want to use a Ruby range object (though, why wouldn't you?).

like image 54
vonconrad Avatar answered Oct 18 '25 18:10

vonconrad



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!