Rails all of a sudden stopped picking up values that are entered with bootstrap-datpicker-rails
, at least I've only noticed it with dates entered with it.
This is a binding.pry call
16: def create
17: @batch = Batch.new(batch_params)
=> 18: binding.pry
19:
20: if @batch.save
21: redirect_to :root
22: else
23: render 'new'
24: end
25: end
[1] pry(#<BatchesController>)> params
=> {"utf8"=>"✓",
"authenticity_token"=>"/0IzN2EfU7MHWnwLeL/RREsqo3C7vtintD8rbmW4rsbmGhV9Q8crc7DerCAnN+CDZ2Sf4OhSgM1aVl8sl3DLfQ==",
"batch"=>{"name"=>"Batch3", "date"=>"02/14/2016"},
"commit"=>"Create New Batch",
"controller"=>"batches",
"action"=>"create"}
[2] pry(#<BatchesController>)> @batch
=> #<Batch:0x007f99ca8b1120 id: nil, name: "Batch3", date: nil, created_at: nil, updated_at: nil, active: nil>
As you can see, parameter batch
has valid date and name values but the @batch
object only picks up the name and not the date. It was working an hour ago and the only thing I changed were some bootstrap elements for the UI.
My strong parameters:
def batch_params
params.require(:batch).permit(:name, :date)
end
The form for entering the values:
<div class='well'>
<%= form_for [@pig, @weight] do |f| %>
<div class='form-group'>
<%= f.label :date %>
<br>
<%= f.text_field :date, "data-provide" => 'datepicker' %>
</div>
<div class='form-group'>
<%= f.label :weight %>
<br>
<%= f.number_field :weight, step: 0.5 %>
</div>
<%= f.submit(@weight.new_record? ? "Add weight" : "Update weight", class:'btn btn-success') %>
<% end %>
</div>
Rails is not able to parse this date format out of the box. But you can add a custom setter to your model to fix that problem:
# in app/models/batch.rb
def date=(string)
write_attribute(:date, DateTime.strptime(string, '%m/%d/%Y'))
end
As you can see from the below result,
This is not a valid date to parse "02/14/2016"
[3] ruby_project » Date.parse("02/14/2016")
ArgumentError: invalid date
[4] ruby_project » DateTime.parse("02/14/2016")
[4] ruby_project » DateTime.parse("02/14/2016")
ArgumentError: invalid date
from (pry):4:in `parse'
[5] ruby_project »
Try with valid date and tell me if it works
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.