Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Range Fields + Rails Forms

Are there any standard ways of integrating the Postgres range types with the Rails form helpers? I basically need a min and max field that get converted into a range on saving. Any ideas?

like image 903
Stussa Avatar asked Jun 23 '15 21:06

Stussa


1 Answers

At first I was thinking about something like this:

class Model
  delegate :begin, :end, to: :range, prefix: true, allow_nil: true # Replace :range with your field name
end

To get methods: range_begin, range_end. I checked documentation and these methods are read only.

So you need also setters:

class Model
  delegate :begin, :end, to: :range, prefix: true, allow_nil: true

  def range_begin=(value)
    self.range = Range.new(value, (range_end || value))
  end

  def range_end=(value)
    self.range = Range.new((range_begin || value), value)
  end
end

If you don't use || in setters, then you get ArgumentError: bad value for range on empty record.

In your views you can use normal inputs for fields range_begin and range_end.

like image 132
Grzegorz Łuszczek Avatar answered Nov 16 '22 23:11

Grzegorz Łuszczek