Search code examples
ruby-on-railsdatetimeform-helpers

Setting Datetime field using Ruby Form helpers


I am trying to set a datetime field using the ruby forum helpers.

<%= form_for @event  do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <strong>Title</strong>
  <div class="field">
    <%= f.text_field :title  %>
  </div>
  <strong>Description</strong>
  <div class="field">
    <%= f.text_area :description, :class => "comment" %>
  </div>
  <strong>Location</strong>
  <div class="field">
    <%= f.text_field :location  %>
  </div>
  <strong>Time</strong>
  <div class="field">
    <%= select_datetime Date.today, :prefix => :start_date %>
  </div>
  <div class="actions">
    <%= f.submit "Add Event" %>
  </div>
<% end %>

In the controller I am doing this: class EventsController < ApplicationController def index @event = Event.new end

  def create
    @event = current_user.events.build(params[:event])
    if @event.save
      redirect_to root_path, :flash => { :success => "#{@event.inspect}!" }
    else
      @feed_items = []
      render 'pages/home'
    end
  end
end

However the date time never sets...what am I doing wrong?


Solution

  • You need to process what you're getting in your controller, like:

    def create
        @event = current_user.events.build(params[:event])
        datetime=DateTime.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i,
                                params[:start_date][:hours].to_i,params[:start_date][:minutes].to_i, params[:start_date][:seconds].to_i)
        @event.datetime = datetime
        if @event.save
          redirect_to root_path, :flash => { :success => "#{@event.inspect}!" }
        else
          @feed_items = []
          render 'pages/home'
        end
      end