Rails 4 - Ransack Form - Format text field - ruby-on-rails

My ransack form has a date to and from search using a datepicker for each. The search and results works great, however I would like to style the form fields so that when the results load, the datetime can be formated just to_date. I am unsure how to access the value used in the form. I could just use the value parameter and apply the styling, but I do not know the variable to use.
<%= f.text_field :order_date_lt, class: "", id: "datepicker1", value: ?????.to_date.strftime('%m-%d-%Y') %>

I found out that in this case #q.order_date_lt, if it is present, will be able to be formatted that way

Related

What is the most native way of adding a date picker to a Ruby on Rails 6 project?

I'm building a simple project where date input plays an important role. I don't want to add an another gem and heavy js library like jquery, bootstrap.
What is the most lightweight solution where I can let users to select/enter date? The pure Ruby way.
Thank you
EDIT:
I use date_field type, but it lets me enter any value. It does not format my input as date.
Code sample:
<%= form.date_field :date %>
SOLUTION (temporary):
Right! I needed to use date_select, not date_field : )
<%= form.date_select :date %>
Your date field should also work but you can try this also , may be this work for you.
<%= form.date_field :date, min: 0.days.ago %>
Rails has a whole heap of in built form helpers for selecting dates and other data types: https://api.rubyonrails.org/v6.0.0/classes/ActionView/Helpers/DateHelper.html#method-i-select_date
I am not sure what you mean by 'pure ruby' as a date picker is html/css with some optional js, but the select_date form helper (and all other rails form helpers) are ruby objects under the hood, which, given arguments, will return HTML.
In addition to the above link, you should check out these docs for how to implement inside a form: https://guides.rubyonrails.org/form_helpers.html#dealing-with-basic-forms
This has to do with the browser support for date_field. It has improved quite a lot recently, see https://caniuse.com/mdn-html_elements_input_input-date

Set and Display Dates in rails via format: %m/%d/%Y

If you want to save a date attribute in a rails form via a text_field: by default rails wants you to put the date in the format of: %Y-%m-%d. ex: '2016-8-25'.
I want to put the date in the format of %m/%d/%Y. ex: '8/25/2016'.
When editing this date attribute: I want it to also display the date in that same format.
I have this specified in my config/locals/en.yml file but it is not working:
en:
date:
formats:
default: "%m/%d/%Y"
If there is another strategy different from above: let me know.
Ultimately: all my date attributes application wide use the bootstrap-datepicker-rails gem. Within forms: this gem wants dates to be in the above format, and it makes sense for dates to be in that format anyways. I do not want to have to override all the writer attributes in order for rails to understand this format.
Update
There appears to be some confusion about my stack overflow question. Users are not actually manually entering dates. They are using a datepicker. And when the user picks a date: it saves the date in a textbox with the format of: mm/dd/yyyy. This is how the clients of this small, in-house app want to display the date (and it makes sense that they want the date displayed this way because they live in the United States and this is a typical date format there).
Ultimately here is the scenario:
Here is the relevant input field in the form:
<div class="field">
<%= f.label :some_date %><br>
<%= f.text_field :some_date, data: {provide: 'datepicker'} %>
</div>
If you manually enter the string: 2016-1-20, and then submit that:
Rails knows how to take that string of 2016-1-20, convert it into a date, and then save that date into the database.
Rails also knows how to redisplay that date within the format of 2016-1-20 if the user wants to go back and edit that date.
I want the exact same setup. The only thing I want to change is the format. Change the format of yyyy-mm-dd to mm/dd/yyyy. So the user would pick a date, and into the input field the value 1/20/2016 would go. That would get submited.
Rails would know how to convert that to a date and save it to the database.
If the user wants to edit this date in the future: it would redisplay in the text field the date in the format of 1/20/2016.
Hopefully this clears up any confusion.
Are you using the l method in your views using this method? It won't work otherwise.
So it looks like this:
<%= l your_date %>
An alternative approach could be creating a file in your config/initializers folder, which can be called date_time.rb for example, and then use this:
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
The best solution I have found is a two-step process:
Allow dates to save within the format of mm/dd/yyyy
Simply add in the american_date gem. And with that: when you enter into a text_field for a date the format of: mm/dd/yyyy (ex: 1/30/2016) it will save the correct date! This works wonderfully with the bootstrap-datepicker-rails gem because when you use the datepicker to pick a date: it loads into the textbox the date in this format.
Display dates in the format of mm/dd/yyyy
however, even with the american_date gem installed: rails still wants to display the date in the yyyy-mm-dd format.
Example: within a text_field, such as: <%= f.text_field :date %>, when the user goes back to edit that date, it will redisplay the date in the format of yyyy-mm-dd which is not what we want. We want rails to redisplay the date in the mm/dd/yyyy format.
Another Example: if you have an erb tag, such as <%= #blog.some_date %> then yet again: rails will display the date in the format of yyyy-mm-dd. Again: this is not what we want. We want that erb tag to automatically redisplay the date in the format of mm/dd/yyyy
To fix this: you have two options:
One option is to open up your config/locals/en.yml file and use the setup specified in the original question of this post. I personally do not like this setup because you then need to remember to use the l method everytime you want to display a date within your app.
The other option (which I like best) is to go to your config/initializers directory and make a new file. Name the file anything you want. I named the file date_display_format.rb. Then within there just put this line: Date::DATE_FORMATS[:default] = "%m/%d/%Y". Now: a date within your erb tags will display in the proper format, and when you go to edit your date attribute within a form: with the text box the date will display in the proper format as well.
For displaying the date in the format you want, you can use the builtin strftime.
For example, if you were displaying the created_at date of an item, you could use the following code to display the saved date in the format of month, day, year. This code would go in a page in your views:
#item.created_at.strftime("%m/%d/%Y")
Or the updated_at date:
#item.updated_at.strftime("%m/%d/%Y")
This would show the created date in the format you want. Then, when you edit it, it will still be displayed in the month, day, year format.

Using a client-side datetime picker in Rails 4

Right now, I have a simple <%= date_select(:record, :date, ampm: false) %> in my view. For the past few days, I've been trying to implement a datetime viewer, and just can't grasp it. I've looked at pickadate.js, Bootstrap 3 Datetimepicker, and others. I understand the jQuery behind them - it's simple to just apply a class to an <input> field.
What I don't understand is how the date gets correctly passed as a part of my Rails form. For example, pickadate.js applies a class to an <input> field, but how does my form_for recognize what attribute it's for? When I use a date_select(:record, :date), I'm telling my app that the input should be recorded in the record model as the date attribute, right? How do I do this with a client-side <input> field?

Ruby on Rails 4: Working with dates between database and forms

I am looking for some help with converting dates back and forth from a form and database. I have been using the following method, but it seems like there should be a better/easier way to manage this.
The code in the view:
<%= f.label :issue_date, "Date Issued" %>
<%= f.text_field :issue_date, class: 'form-control', :value => #license.issue_date.strftime("%m-%d-%Y") %>
The code in the controller:
params[:license][:issue_date] = DateTime.strptime( params[:license][:issue_date], "%m-%d-%Y").strftime("%Y-%m-%d")
params[:license][:expiration_date] = DateTime.strptime( params[:license][:expiration_date], "%m-%d-%Y").strftime("%Y-%m-%d")
My concern is that this depends too much on the input format being correct. For instance, if the inputs 4/2/2015 instead of 4-2-2015, it breaks the code. I would appreciate any help or advice! I have been reading a lot of posts on dates, but nothing specific to answering this question.
Unfortunately, a date input with good UI is hard to set up in Rails, at least in my experience. If you are willing to compromise a bit on the UI, the simplest solution is to use the built-in date_select helper:
<%= f.date_select :issue_date %>
This will generate three select inputs, like this:
Rails will automatically handle translating the submission from these three inputs into a proper date in the database. Again, the UI is not great, but it does solve the date format validation problem.
Later, if you decide to use a Javascript date picker instead, set up the JS to ensure that the date value is always submitted to the server in YYYY-MM-DD format, which is what Rails expects.

Is it possible to have date_select with year text box?

I'm looking to create an ancestry type webpage with a date field that allows user to enter a date going back to thee digits. This makes date_select with dropdown boxes and the jquery datepicker very un-user friendly.
Does anyone know a good way to display a text box for the year but a dropdown for month and day?
I'm hoping to use the "intelligence" of date_select while still allowing the user to enter the year in a more user friendly fashion (the textbox).
Thanks for any help you can give me!
With great respect to the developers of Rails, the date_select usability is pretty weak for almost any case :-)
Unlike other field types, the date_select helper generates three select tags with special names and ids, one each for the year, month, and day elements. It's the naming convention that allows controller code to auto-magically re-assemble the inputs into a (single) date when it is processing the params array.
Sorry, I don't have a handy example of the naming format (since I never use date_select), but if you look at the names of the fields, you might be able to mimic the behavior without too much hackery by using the :discard_year option. That gets you the month and day fields, and a hidden field (I think) containing the current year.
If you're not averse to a little JS or CoffeeScript, you could modify the input field after the DOM is loaded, by removing the hidden "type" attribute (thus making it a simple text field) and setting its value to be empty.
I would choose between three options
1-Use a date_select only for day and month and a text field with some javascript for the year
Date_select accepts a :discard_year option, if you set it to true, the year field is rendered as a hidden_field so there's no select/dropdown http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select
Then you put a text_field and bind to the keyUp event and modify the value of the hidden year field
The most important problem about this is that, if the user has javascript disabled, the value of the text field will never be set to the hidden field and that's a problem.
2-Use a date_select only for day and month and a text field
I'm not sure if you can do this option, you can try using the same date_select as above and set the name of the input field with the name of the year field. The problem is that date_select will put a hidden field with that name and you put another field with the same name and the value sent on submission may not be what you want... You should see if it's posible.
3-Use a date_select and add extra functionality using Choosen http://harvesthq.github.com/chosen/
Put the date_select as always and set the start_year and end_year that you want, then replace the selects with choosen selects, the choosen select includes a text field to search between the years of the select
Choosen gives you a nice and consistence look almost crossbrowser (didn't test it on old IE versions), you get the text input for user-friendliness and, if javascript is disabled, the user still have the three selects.
I would definitelly use number 3, but maybe you don't want to add a plugin.
Experimenting with the Javascript route suggested by Tom, I came up with something like the following:
<%= f.date_select :birth_date %>
<script>
var date_field =
document.getElementsByName('ancestor[birth_date(1i)]')[0];
var new_html = '<%=
f.text_field 'birth_date(1i)', :value=>(f.object.birth_date.strftime("%Y") rescue "") %>';
date_field.outerHTML = new_html;
</script>
(Improvements welcome)

Resources