Date is not saving in ruby on rails - ruby-on-rails

I have added datepicker in _form.html.erb page to pick date at the time of creation. but when i click on create button it is showing field cannot be blank. when i see the params, it is showing "dob"=>"08/17/2012", but it is not passing the validation. I am not sure weather it is a format problem. can anyone help me to solve this problem. thnks
my application.html.erb file contains:-
<%= javascript_include_tag "jquery-1.8.0.min" %>
<%= javascript_include_tag "jquery-ui-1.8.23.custom.min" %>
<!--%= javascript_include_tag "application" %-->
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
and _form.html.erb contains:-
<div class="span10 date-wid">
<%= f.text_field :dob, :id => 'datepicker' %>
</div>

It probably is your format. The correct format to save time to a database is this
For the date , March 1st, 2012 or 3/1/2012 :
20120301
So the order goes Year, Month, Day in the structure of 4 digits, 2 digits, 2 digits. Protip, you can add more which would be your hours minutes and seconds as well.
So make sure your datepicker is producing that as well :
$(".date-single-view").datepicker({
dateFormat: "yyyy-mm-dd"
});
That will add -, but it should still work. You can also do other things like have the datepicker on select drop the data format to a hidden input div, and the input field is just for show.
You can also use the Chronic gem to properly parse various different means of time.
https://github.com/mojombo/chronic

Related

Rails form flipping days and months

I have a form that received dates via two variable :start and :end. When I input the date they look right, but when I save, the model receive a date with the days and months flipped, and when the day is greater than 12, say 13th of March, it will simply show nil error.
My form field look like:
<div class="input-group date" id="datetimepicker4" data-target-input="nearest">
<%= f.text_field(:start, value: f.object.start ? f.object.start.strftime('%m/%d/%Y %l:%M %p') : nil, class: "form-control datetimepicker-input", data: {target: "#datetimepicker4"}, placeholder: "#{t :From}", required: true) %>
<div class="input-group-append" data-target="#datetimepicker4" data-toggle="datetimepicker">
<div class="input-group-text"><span class="fas fa-calendar-alt"></span></div>
</div>
</div>
Same for :end variable
The input form looks like :
The results looks like:
Looks like you try to use US date format, but rails is parsing submitted params with month and day switched. I am not sure if you would prefer to use US or international date format and I advise you to check how rails is handling parsing submitted params.
Also, have a look at defaults of calendar date time picker you use.
UPDATE.
I will try to provide more details. In one of my projects I am using a similar date time picker that looks like this
When submitted you will have the following params in our controller
{"date_time_picker_input_field"=>"2020-01-20"}.
The reason my date time picker formats date as YYYY-MM-DD is that in the view code I am using an option that is taken by datetimepicker code upon initialisation, something similar to
date_format: 'yyyy-mm-dd',
(this can be different in the date time picker you use and I suggested earlier to check documentation on options you can use).
I don't have to use strftime on date time provided to text_field, because date time JS code will format the date in format of your choice.

Rails date_field not working in IE

I have a search built on date fields. I want to use the date_field instead of date_selector if possible.
The date field works fine in chrome. However, in IE 11, the placeholder and controls do not work. The date select does work in IE.
<%= f.date_field( :req_resolution_from_date) %>
<%= f.date_select( :req_resolution_to_date) %>
In chrome, both date_field and date_select work.
However, in IE, only the date_select works
Is there any way to get the date_field to show in IE with the date controls?

rails dyamically add fields to nested form

I have followed Ryans railscast #196 (revised) in order to dynamically add and remove fields to a nested form. It seems to be working just fine but I am having two issues.
I have 2 fields in the nested form (child area) that use the JQuery datepicker and as such have a class on them in the partial that displays the initial records. Initially the form is created with just 1 child. On this 1st child row the datepicker works just fine. However, when a new row is added the 2 fields with the datepicker no longer work. I believe the issue is due to the fact that when the new record gets created it does not assign the class to them, therefore the JS will not work :( No idea how to go about attempting to fix this, if it's even possible. If this is not possible then do I need to have a button to add a new record that will basically do this and refresh the form? I am hoping there's a way to do this dynamically since it just looks smoother.
When I go to edit the above record the same 2 fields are not showing the actual dates. The dates are fine and I can see that they are saved in the DB. I have another form that has a date field with the datepicker but that field is at the header and it is showing a value when editing the field. Obviously, the code I have to set the value of the date field is just not working. Again, would appreciate some help. The code is below for the partial view of these two fields.
<% fromdate_display = :fromdate %>
<%= f.text_field fromdate_display, placeholder: "mm/dd/yyyy", required: true, id: "price_fromdate", value: :fromdate.try(:strftime, "%m/%d/%Y") %>
<%= f.hidden_field :fromdate, id: "price_fromdatealt" %>
<% todate_display = :todate %>
<%= f.text_field todate_display, placeholder: "mm/dd/yyyy", required: true, id: "price_todate", value: :todate.try(:strftime, "%m/%d/%Y") %>
<%= f.hidden_field :todate, id: "price_todatealt" %>
I have tried changing the value: to be something as follows, but that throws an error:
value: #plan.plan_prices.fromdate.try(:strftime, "%m/%d/%Y")
Error message thrown:
undefined method `fromdate' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_PlanPrice:0x36eb428>
I think the datepicker inputs dont work because are added dynamically after the datepicker plugin is loaded. Try to call the js plugin after you add a new input, maybe in the click event of link that add the inputs. Or try use this gem https://github.com/nathanvda/cocoon. By the way, what plugin you use for datepickers?

Argument out of range Rails 4 and bootstrap3-datetimepicker-rails

I'm using the bootstrap3-datetimepicker-rails gem to let users store the scheduled_date of a WorkOrder in my application (a 'DateTime' property), but I'm getting an argument out of range error when the user submits the form to create the WorkOrder, and the date is very different than what was selected whenever the user pops open the edit screen. The funny thing is that it used to work, but I don't know what code could have changed to break it.
I added the required dependencies & included the proper directives in my CSS/JS files:
gem 'momentjs-rails', '~> 2.5.0'
gem 'bootstrap3-datetimepicker-rails', '~> 3.0.0'
As far as I can tell, my code looks identical to the example on the documentation. Here's the snippet of my form:
<div class="row">
<div class="col-md-4">
<div class="form-group">
<%= f.label :scheduled_date %>
<div class='input-group date'>
<span class="input-group-addon"><span class="fa fa-calendar"></span></span>
<%= f.text_field :scheduled_date, class: 'form-control input-lg', id: "service_date_picker" %>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#service_date_picker').datetimepicker({
icons: {
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-arrow-up",
down: "fa fa-arrow-down"
}
});
});
</script>
EDIT (forgot to add controller code - super simple):
work_orders_controller.rb
def create
#work_order = WorkOrder.new(work_order_params)
... [it errors on the line above]
end
And my parameter whitelist:
def work_order_params
params.require(:work_order).permit(:caller_name, :brief_job_details, :contract_price, :quoted_by, :job_description, :scheduled_date, :time_materials_details, :sheduled_time, :contact_name, :payment_method, :notes, :customer_id, :job_site_id)
end
And an example of the parameters that give the argument out of range error when I save the form:
work_orders_attributes"=>{"0"=>{"caller_name"=>"Justin", "time_materials_details"=>"", "contract_price"=>"", "quoted_by"=>"", "payment_method"=>"", "job_description"=>"", "scheduled_date"=>"05/23/2014 1:28 PM", "notes"=>""}}
Same as my customers_controller.rb where I have a nested form for a WorkOrder inside of the new customer form (everything else on that form works perfectly):
def create
#customer = Customer.new(customer_params)
... [errors above]
end
The date and time saves correctly if it is within 24 hours of now, but even when it saves correctly, the date displays completely weird and unformatted in the text field when I go to edit that WorkOrder. For instance:
When I select the date from the date picker: 05/06/2014 10:28 AM
When I edit the WorkOrder: 2014-06-05 10:28:00.000000
Any ideas? Any preference for whether I should make that field a Date, Time, or DateTime (currently)? Right now, we're working in Central time zone, but that won't always be the case.
Thanks in advance for pointing me in the right direction!
#Uri Agassi is right: it's the values that you're passing to create the WorkOrder that are the most relevant here.
Try putzing around with the custom date formatting options provided to you by bootstrap-datepicker. If you can get a format that looks good and is easy to parse on the backend, then you'll want to intercept that parameter before it goes to the model for validation.
Regardless of what you'll go with for date formatting on the client-side, you'll still want to parse it into a useable Date or DateTime object server-side in your controller. Check out DateTime#strptime. You can also call #strptime on Date.
Untested, but the idea is there:
def create
order_params = work_order_params
order_params[:scheduled_date] = Date.strptime(order_params[:scheduled_date],
'%m/%d/%Y %I:%M %p')
#work_order = WorkOrder.new(order_params)
end
You can remove the modifications from the Controller all together by updating the values in the model. I feel this is a much cleaner (and reusable) approach.
class Work < ActiveRecord::Base
def scheduled_date=(date)
begin
parsed = Date.strptime(date,'%m/%d/%Y %I:%M %p')
super parsed
rescue
date
end
end
end
It's me helped:
To file application.js writing to end file:
$(function() {
$('.datepicker').datepicker({format: 'dd-mm-yyyy'});
});
This plugin uses moment.js. Basically you need to choose the time format you would like.
example
$(function () {
$('#datetimepicker').datetimepicker({format: 'MMMM Do YYYY, h:mm'});
});

Styling the date fields of a Rails date_select

In Rails' forms, date select drop-downs are easy:
<%= f.label :my_date %>
<%= f.date_select :my_date %>
Then I get 3 select drop-downs for the year, month and day. Is there an easy way to add HTML between these select elements without using JavaScript? I want to be able to style and label them nicer.
Convert it to a text field and add a JQuery datepicker or similar.
Theres a good guide here, http://railscasts.com/episodes/213-calendars
You can easily style them with CSS as each part of date_select is postfixed with '_1i', '_2i' etc . For a date_select with id 'my_date' you can use
#my_date_1i // the year
#my_date_2i // the month
#my_date_3i // the day
Hope this helps
Cheers

Resources