正在加载从 datetime_select 帮助程序提交的日期时间值,因此我可以将其与现有保存的数据进行比较。
我正在使用以下代码,但感觉有点麻烦。
DateTime.parse("#{params['start_date(1i)'].to_i}-#{params['start_date(2i)'].to_i}-#{params['start_date(3i)'].to_i} #{params['start_date(4i)'].to_i}:#{params['start_date(5i)'].to_i} -500")
有没有更简单的方法来构建日期时间对象?
编辑:
这是我的表单代码:
= form_for(@charity) do |f|
- if @charity.errors.any?
#error_explanation
%h2
= pluralize(@charity.errors.count, "error")
prohibited this charity from being saved:
%ul
- @charity.errors.full_messages.each do |msg|
%li= msg
.field
= f.label :name, 'Name *'
= f.text_field :name
%fieldset
%legend Dates in Eastern Standard Time
.field
= f.label :start_date, 'Start Date *'
= f.datetime_select :start_date, :default => DateTime.now
.field
= f.label :end_date, 'End Date *'
= f.datetime_select :end_date, :default => DateTime.now
.field
= f.label :percentage, 'Percentage of sales to be donated *'
= f.text_field :percentage
.field
= f.label :charity_number, 'The identification number for your charity *'
= f.text_field :charity_number
.field
Donation options:
%span{ title: "Dollar amounts that you wish to allow people to donate on top of their order.", class: "tooltip_hover" }= image_tag "question.png"
- DonationOption.all.each do |option|
= f.label option.id, number_to_currency(option.amount, unit: "$"), class: "donation_label"
= check_box_tag "charity[donation_option_ids][]", option.id, @charity.donation_option_ids.include?(option.id), class: "donation_check"
.actions
= f.submit nil, class: "btn-primary"
控制器:
def update
@charity = Charity.find(params[:id])
respond_to do |format|
if @charity.update_values(params[:charity])
format.html { redirect_to @charity, notice: 'Charity was successfully updated.', :charity => @charity }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @charity.errors, status: :unprocessable_entity }
end
end
end
update_values 方法:
def update_values(attributes)
s_date = DateTime.parse("#{attributes['start_date(1i)'].to_i}-#{attributes['start_date(2i)'].to_i}-#{attributes['start_date(3i)'].to_i} #{attributes['start_date(4i)'].to_i}:#{attributes['start_date(5i)'].to_i} -500")
attributes.delete('start_date(1i)')
attributes.delete('start_date(2i)')
attributes.delete('start_date(3i)')
attributes.delete('start_date(4i)')
attributes.delete('start_date(5i)')
# if the charity has not started yet
if DateTime.now.utc < self.start_date.utc
self.start_date = s_date
attributes.merge!(reset_create_job)
end
e_date = DateTime.parse("#{attributes['end_date(1i)'].to_i}-#{attributes['end_date(2i)'].to_i}-#{attributes['end_date(3i)'].to_i} #{attributes['end_date(4i)'].to_i}:#{attributes['end_date(5i)'].to_i} -500")
attributes.delete('end_date(1i)')
attributes.delete('end_date(2i)')
attributes.delete('end_date(3i)')
attributes.delete('end_date(4i)')
attributes.delete('end_date(5i)')
if DateTime.now.utc < self.end_date.utc
self.end_date = e_date
attributes.merge!(reset_delete_job)
end
self.update_attributes(attributes)
end