I use rails 3.1, formtastic 2.0.2 and datepicker ui
I made datepicker_input.rb:
class DatepickerInput < Formtastic::Inputs::StringInput
include Formtastic::Inputs::Base
def input_html_options
super.merge(:class => "datepicker")
end
end
In application.js I wrote:
$('input.datepicker').datepicker()
I use it in my form like :as => :datepicker. I see calendar, pick date and everything is fine except for it doesn't fill column in my model. The only thing that I noticed is that when I fill first date and then all the other fields - it works. When date field is the last - it doesn't work. There is no errors, params[:model_name][:date_field] is not empty just nil in place of date that I chose.
Error was in date format - database just couldn't take format that returned datepicker.
Related
My ActiveAdmin model creation forms (ie. /admin/<model>/new) are using an awkward set of dropdowns for dates and datetimes.
I'd like to use pickers instead. But all the documentation I've found about using a datetime picker appears to require rewriting the whole form. There doesn't seem to be a way to change just one input, nor an equivalent of preserve_default_filters!.
I'd like to either change the default for all date and datetime columns, something like...
config.datepicker = ...
Or per column, like...
column :signed_up, as: :datetime_picker
EDIT
By default I get new and edit forms equivalent to this.
form do |f|
f.semantic_errors
f.inputs
f.actions
end
If I want to change signed_up to use a datepicker, I have to repeat all the columns supplied by default just to change the input type of one column.
ActiveAdmin.register Thing do
form do |f|
t.semantic_errors
t.input :name
t.input :this
t.input :that
t.input :signed_up, as: :datepicker
t.input :other
t.input :thing
t.input :left
t.input :right
t.actions
end
end
That's a lot of unnecessary repetition, and the formatting doesn't come out right. I'm looking for a way to change the input presentation of one column, or one type, without having to manually write the whole form every time.
Try the DateNTimePickerActiveAdmin Rubygem. It works really well and is customisable according to your project.
You can find the documentation here: https://github.com/NikhithaGraceJosh/date_n_time_picker_activeadmin
From the docs:
Gemfile
gem 'date_n_time_picker_activeadmin'
Code Sample (In your form)
f.input :column_name, as: :datetimepicker
CSS
In active_admin.scss, add the line,
#import date_n_time_picker_activeadmin
JS
In active_admin.js, add the line,
//= require date_n_time_picker_activeadmin
Hope it's useful!
I managed to monkey patch Active Admin behavior, to use :datepicker instead of :date_select.
In your config/application.rb, add following patches
Bundler.require(*Rails.groups)
// Start patch
module ActiveAdminFormBuilderPatch
def default_input_type(*_args, **_kwargs)
ret = super
ret == :date_select ? :datepicker : ret
end
end
ActiveAdmin::FormBuilder.include ActiveAdminFormBuilderPatch
// end patch
module YourApp
class Application < Rails::Application
// configs
end
end
Note
Confirmed this to be working on activeadmin version 2.9.0.
I used activeadmin_addons which does a lot of useful things, including using DateTimePicker for input, but not filters.
To get filters I use active_admin_datetimepicker which makes jQuery DateTimePicker available for inputs (:date_time_picker) and filters (:date_time_range). Then I monkey patched ActiveAdmin to use it by default.
# config/initializers/active_admin.rb
# Make the default filter type for a DateTime to be the DateTimeRange picker.
class ActiveAdmin::Filters::FormBuilder
protected
alias_method :original_default_input_type, :default_input_type
def default_input_type(method, options = {})
case column_for(method)&.type
when :datetime
return :date_time_range
end
original_default_input_type(method, options)
end
end
Has anyone run into this problem? I have a User object and a simple_form which asks for the User's birthday.
<%= f.input :birthday, as: :date, start_year: Date.today.year - 70,
end_year: Date.today.year, order: [:month, :day, :year], label: false %>
Any date I pick I can only pick a day up to the 12th of each month. If I pick 13th or higher simple_form says "Please enter a valid date". Very strange.
I got this code from https://github.com/plataformatec/simple_form and all it says about this code is "SimpleForm accepts same options as their corresponding input type helper in Rails". Does anyone know where the corresponding input type helper in Rails is documented?
I would guess that you've confused :day and :month somewhere.
Or maybe, put differently, you want to use the American format and instead you're using the european format (or the reverse). Not sure it will help, but see this link:
How can I use US-style dates in Rails using Ruby 1.9?
I'm using Rails 3 and failing to submit a form because one of the fields fails to pass validates_presence_of. My model is called dinner, and the field, which is used in conjunction with a datepicker, is called date.
views/dinners/new.html.erb:
<%= f.text_field :date, id: "datepicker" %>
models/dinner.rb:
attr_accessible :date
validates_presence_of :date
dinners_controller.rb:
def create
#dinner = Dinner.new params[:dinner]
if #dinner.save
flash[:notice] = "Dinner created successfully."
redirect_to controller: 'dinners'
else
flash.now[:alert] = #dinner.errors.full_messages.join("<br>").html_safe
render action: "new"
end
end
Whenever I fill out all of the fields, including date, I get the error "Date can't be blank", even though it is not blank. What's going on here?
I've found the answer.
My date column was of type date, and before validation Rails ran .to_date on it. Unfortunately, the datepicker that I use creates dates in the American mm/dd/yy format, which Rails can't handle, so .to_date returned nil. That's why the date failed validation: because it really was nil, even though the POST request was fine.
I chose the easy solution and changed the default date of datepicker, as shown here.
Note: For my version of datepicker, I had to use format instead of dateFormat, and also had to use yyyy-mm-dd instead of yy-mm-dd because Rails String#to_date thinks that the year "13" is literally '0013' and not '2013'.
I have a Rails 3 application with a prescription model. The model has a number of fields, two of them are to calculate and display the duration of a prescription.
At the moment the user enters a value in a text field such as '3 Months' and then manually changes a datetime input to three months from now. This seems like a perfect form to automate for the user.
Currently the fields are like this:
Duration of Treatment
<%= f.text_field :duration, :class => "input-text" %>
Date of Expiry
<%= f.datetime_select :expiry, :order => [:day, :month, :year], :class => "input-text" %>
So, my question. How can I create two dropdown lists for the duration field such as:
[1] [Day]
The user can select the number from the first list and in the second they can choose Day, Week or Month.
The value they pick using the duration select boxes would be saved as a text string e.g. "1 month" and the value of the Time.now in 1 month would be saved as a datetime value in the expiry column.
Is something like this possible to do? If so, how?
I'll provide an example of how you'd use the chronic gem, since it seems tailor-made for this purpose:
require 'chronic'
duration = "3 months" # => "3 months"
Time.now # => 2012-07-09 18:43:50 -0700
Chronic.parse(duration + " from now") # => 2012-10-09 18:43:55 -0700
If I understand your use case correctly, you can then just get rid of the datetime select entirely. Ask the user for the text duration and assign that to the text attribute. Then use chronic to determine the time value from the text parameter and assign that to the datetime attribute. For extra credit get the parsed time value asynchronously and display it on the page before they submit the form so they can see that what they are submitting makes sense.
You can just do something easy like:
Time.now + 10.days
Source: How to add 10 days to current time in Rails
And how to do drop-downs?
Drop down box in Rails
Assuming the prescription is valid at the time of object creation, you can store the start date in the database as the current time Time.now (may want to convert to a datetime) and then based on the drop-down, add the amount of time until it expires like off the top of my head:
eval "Time.now + #{params[:prescription][:amount].#{params[:prescription][:time_type]}"
Hope that made sense. I would look up a better way to add the time though that maybe doesn't use eval. Heres the time reference: http://api.rubyonrails.org/classes/Time.html
First, change your duration field to a select menu with 1-30, or whatever numbers you want.
Then in the controller action that handles your form:
#prescription = Prescription.new(params[:prescrption])
#prescription.duration = "#{pluralize(params[:prescription][:duration], params[:prescription][:expiry])}"
if params[:prescription][:expiry] == "Day"
#prescription.expiry = Time.now + params[:prescription][:duration].days
elsif params[:prescription][:expiry] == "Week"
# Put week logic here
elsif params[:prescription][:expiry] == "Month"
# Put month logic here
end
# Put the rest of the #prescription.save stuff here.
It's a little verbose, but I think that's kind of the way it is with the way time is set up in Ruby...
I asked a question regarding this yesterday, but it was muddled and didn't make sense, so I'm going to boil it down to the core issue.
I have an entries table. When a new record is saved, the entries_controller adds a time to the date column, which is recorded as a datetime. In the new method, I declare a new DateTime as so:
#entry.date = DateTime.new( params[:year].to_i, params[:month].to_i, params[:day].to_i )
I then include it as a hidden field with formtastic:
<%= f.input :date, :as => :hidden %>
Once the entry is saved to the database, the date field looks like 2011-02-10 00:00:00. Everything is working as planned so far, but when I try to retrieve that entry by querying against the date field, I get nil.
I've tried:
search_date = DateTime.new(2011,2,10)
Entry.find_by_date(search_date)
=> nil
I've even tried to search by string, which doesn't make sense since it's a datetime field.
search_time = '2010-02-10 00:00:00'
Entry.find_by_date(search_date)
=> nil
What am I doing wrong here? Why can't I retrieve the record by date?
Would this work for you?
Entry.where("date = #{search_date}")
I just tested this in Rails 3.0.4, mysql2 0.2.6 and
Entry.find_by_date(DateTime.new(2011,2,10))
works.
Having said that, why are you using a datetime column to save a date? Other than it just being a bad idea, you possibly could be running into some kind of timezone issues based on your rails and sql settings. Some automatic timezone conversion could explain the behaviour you are observing but that's just a guess. Please check the development server logs to see if rails is indeed generating the query you wish it to generate.