0

I've got a record with a period field of type tsrange. I'm making a form to create it, and I'd like to keep using rails form helpers - I was wondering if there was some kind of convention for setting the date for the range's begin and end?

In my view this:

<%= form_with(model: @record) do |record_form| %>
<%= record_form.datetime_local_field :period %>
<% end %>

Results in an error undefined method 'strftime' for Mon, 01 Jan 1996 09:00:00 +0000..Mon, 01 Jan 1996 17:00:00 +0000:Range

Which makes sense, since I can't directly create one input for the range, but there doesn't seem to be any way to unpack the range attribute into its begin and end methods with something like

<%= record_form.datetime_local_field :period_begin %>

Since that errors with

undefined method 'period_begin' for #<ShiftPeriod id: nil, shift_pattern_id: nil, period: Mon, 01 Jan 1996 09:00:00 +0000..Mon, 01 Jan 1996 17:00:00 +0000, created_at: nil, updated_at: nil>

Other than building the inputs manually, is there any way to build the inputs for this range field type? Thanks!

4

1 回答 1

1

I think you'll have to add custom getters and setters for those values:

def period_begin
  # using read_attribute because I'm redefining the `period` getter at the end
  @period_begin = read_attribute(:period)&.begin
end

def period_end
  @period_end = read_attribute(:period)&.end
end

def period_begin=(value)
  @period_begin = value
end

def period_end=(value)
  @period_end = value
end

def period
  period_begin..period_end if period_begin && period_end
end

Not a 100% sure about this (I've never used the tsrange type), but hope the idea (maybe the implementation of each getter/setter is not the correct one) helps you.

Then period_end and period_begin should work when rendering the form and should work when setting the attributes when you submit the form.

于 2021-12-21T23:24:35.213 回答