Setting Datetime field using Ruby Form helpers
I am tryin开发者_StackOverflow中文版g 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?
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
This question is almost half a decade old but just in case it helps someone in future, there's a simpler way to create objects of a model with datetime attribute.
Replace <%= select_datetime Date.today, :prefix => :start_date %>
with <%= f.datetime_select :datetime %>
And define the create action in controller as below.
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
精彩评论