ruby-on-railsrubyactiveadminformtastic

Edit form not grabbing value used


I have a form (formtastic) that is using the Date::DAYNAMES helper to output the days of the week in a select box:

days = Date::DAYNAMES
q.input :day,
collection: days,
as: :select

This works and outputs the days of the week starting from Sunday, however when it comes to editing that same form the field in question does not remember what day I have previously selected, it just returns the same dropdown (defaults to a blank field).

Form:

# Activity Date/Time Entry
f.inputs class: 'activityDayTime' do
  f.has_many :activity_dates do |q|
    days = Date::DAYNAMES
    if q.object.new_record?
      q.input :day,
              collection: days,
              as: :select
      q.input :time_from
      q.input :time_to
    else
      q.input :day,
              collection: days,
              as: :select
      q.input :time_from
      q.input :time_to
      q.input :_destroy,
              as: :boolean,
              required: :false,
              label: 'Remove Day/Time'
    end
  end
end

How can I tell the form to default to the saved day within the edit form?

Edit

After checking the DB it seems the days is actually saving (showing as nil), so there seems to be something wrong with Date::DAYNAMES saving into a date field

Edit 2

I have changed the date field to a string field but the day still saves as nil.


Solution

  • # app/helpers/collection_helper
    module CollectionHelper
      def days_collection
        (0..6).map { |wday| [Date::DAYNAMES[wday], wday] }
      end
    end
    
    # app/views/posts/_form.html.erb
    . . .
      = select_tag :month, options_for_select(days_collection, Time.now.day) # or collection helper
      # simple_form
      = f.input :month, as: :select, collection: days_collection
      # formastic
      = f.input :author, as: :select, collection: days_collection
    . . .
    

    Explanation:

    A day stores as integer in rails

    Post.first.created_at.wday # => 2
    

    So we need to associate day name with its number

    Date::DAYNAMES
    => [ "Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" ]
    

    This we can achieve with the code (one of implementations of it)

    (0..6).map { |wday| [Date::DAYNAMES[wday], wday] }
    # => [ [ "Sunday", 0],[ "Monday",1], ["Tuesday", 2], # end etc
    

    This is format of array which is needed for collection builder for formastic and simple form also.
    Wish it helps.