ck3g
ck3g

Reputation: 5929

What is the best way to handle date in a Rails Form Objects

I'm using Form Object as described in 7 Patterns to Refactor Fat ActiveRecord Models #3 and currently I have an issue with storing date.

Here's what I've done:

class MyModelForm
  # ...

  def initialize(my_model: MyModel.new, params: {})
    @my_model, @params = my_model, params
    @my_model.date_field_on = Date.from_params @params, "date_field_on" if @params.present?
  end
end

Where Date.from_params is implemented like:

class Date
  def self.from_params(params, field_name)
    begin
      year = params["#{ field_name }(1i)"]
      month = params["#{ field_name }(2i)"]
      day = params["#{ field_name }(3i)"]

      Date.civil year.to_i, month.to_i, day.to_i if year && month && day
    rescue ArgumentError => e
      # catch that because I don't want getting error when date cannot be parsed (invalid)
    end
  end
end

I cannot just use @my_model.assign_attributes @params.slice(*ACCEPTED_ATTRIBUTES) because my params["date_field_on(<n>i)"] will be skipped and date will not be stored.

Is there a better approach to handle date fields using Form Objects?

Upvotes: 4

Views: 1000

Answers (1)

ck3g
ck3g

Reputation: 5929

As @davidfurber mentioned in comments it works great with Virtus gem.

class MyModelForm
  include Virtus

  # ...
  attribute :date_field_on, Date

  def initialize(params: {})
    @my_model.assign_attributes params
  end
end

Upvotes: 1

Related Questions