Date Issue with Ruby on Rails - ruby-on-rails

I just working on a simple Ruby on Rails application that keeps the data information of staff, but I realized that I needed a way to check that the date of employment will definitely need to be the beginning of the date of resignation.
<div class="field">
<%= f.label :date_of_employment %><br />
<%= f.date_select :date_of_employment, :start_year =>1990 %>
</div>
<div class="field">
<%= f.label :date_of_resignation %><br />
<%= date_select :date_of_resignation, :start_year => Time.now %>

You should check validates timeliness gem, if you are happy to add outside code to your project. It adds all kinds of time/date based validations.
Including validating that one field is before/after another. For instance, the following commands could be used in you model:
validates_datetime :date_of_resignation, :after => :date_of_employment
This gem doesn't rely on javascript to work, it's pure Ruby.

One of the simple solution you can consider is to have a javascript function to verify these two date on form submit. This way your server does not need to process invalid data.
We can perform validation at Rails model level before saving to database. For example these lines of code in the model will validate the data before saving
validate :verify_date
def verify_date
errors.add("Invalid date") if date_of_resignation < date_of_employment
end

Related

Rails Form - Check for pre-existing data and populate fields

I'm working on a rails app that allows field agents to report ticket(s) on behalf of clients. I am capturing the data using a model called "submission" where the agents can input the client's details and submit one or more tickets for the client.
I want to ensure that if a client already exists then a new record is not created for the same client. I would also like to ensure that if a client has a name similar to a pre-existing record then the clients don't get mixed up e.g: 2 people named John Smith.
My current submission form:
<%= form_for(#submission) do |f| %>
# some submission fields here ...
<h4>Client Details</h4>
<%= f.fields_for :client do |c| %>
<div class="row">
<div class="field col-xs-6">
<%= c.label :first_name %><br>
<%= c.text_field :first_name, class: 'form-control' %>
</div>
<div class="field col-xs-6">
<%= c.label :last_name %><br>
<%= c.text_field :last_name, class: 'form-control' %>
</div>
</div>
# more client fields....
<% end %>
<% end %>
How can I add a function to check for existing records that match the first and last names when you fill in the fields? Also, how can I ensure that if 2 clients exist with the same name then this can be identified? Could I maybe use the phone number as a unique identifier?
I know my question is a bit vague but I am unsure of how best to tackle this issue (autocomplete? maybe a checkbox that has options for new or existing client?)
Any help would be most appreciated.
You probably want to use Rails validations to ensure the first name and last name of client will not repeat. For example:
class Client < ActiveRecord::Base
validates :first_name, uniqueness: true
validates :last_name, uniqueness: true
end
But this will reject any that has same first name but different last name or the other case. In this situation you might search for custom validation method:
class Client < ActiveRecord::Base
validate :same_full_name
def same_full_name
# or different logic/additional condition
if Client.exists?(first_name: first_name, last_name: last_name, phone_number: phone_number)
errors.add("Client with this name exists.")
end
end
end
This will prompts error when user tries to submit the form. When Rails validation failed they will be redirected to this page(assuming that standard REST actions applied) and see the error message(if there's any flash or error message in your view).
If instant error prompt is preferred, you may want a JavaScript client integration with Rails validation such as client_side_validations gem, or use jquery validation for pure Javascript validation.
For the problem stated in the comment:
If a client does already exist in the database, how can I populate the form with this data and save the submission with the same client?
This depends on the web flow, another of the solution might be using ajax to call a controller action to check whether the client exists. If it does then you can use jQuery to populate the returned client data(from the controller) to the form, instead of doing the validation.

Ruby on rails cant get values from textfield to array

I need to get an array of strings from f.text_field and store it into a database.
<div>
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div>
<%= f.label :tags %>
<%= f.text_field :tags%>
</div>
tags is an attribute and it is in an array. Name stores into the database correctly but nothing to tags.
How can i do this?
Thanks
You'll probably want to either parse that on the client side with JS to create an array that gets stored in a hidden field, or something similar. Alternatively, you should pass the raw text to the controller and parse it ruby. You should probably do the latter as you will probably want to sanitize the input.
There is a very good gem available for handling tagging. It's called acts-as-taggable and is found here https://github.com/mbleigh/acts-as-taggable-on

How do you allow a null date entry with ruby on rails?

I'm brand new to ROR. I'm having a pretty simple problem that I can't find the solution to anywhere. In one of my projects I have a field to enter the date. The problem is that for lots of the data that I gather the date is missing. I don't know how to make that null. My form.html looks like this.
<div class="field">
<%= f.label :date %><br />
<%= f.date_select :date %>
</div>
I imagine that just need to add something to this to allow there to be no date entered. Does anyone know how to allow null entries in a date field?
Thanks
You can use the following option to allow blanks if that's what you mean:
<%= f.date_select :date, :include_blank => true %>
You can then leave it blank, so it becomes NULL in your DB.

Rails and date_select

I am trying to use date_select with some of my forms.
<div class="field">
<%= f.label :begin_date %>
<br/>
<%= f.date_select(:begin_date,:start_year => Time.now.year) %>
</div>
Reading through the documentation, I was expecting to get three select tags. What I got was: begin_date(1i), begin_date(2i), begin_date(3i)
If I include these in my model:
attr_accessible :begin_date(1i), :begin_date(2i), :begin_date(3i),
The IDE does not like it. What am I doing wrong? Also, is there a date select method that would return the values in a single tag, instead of 3?
You can just do attr_accessible :begin_date, and it will stitch together the date components into a single Date value for you.

Rails: Human-friendly date format for text_field

I have a birth_date field that is stored as a datetime value. The default rails form helpers spit out a not-too-friendly format, e.g. "2008-06-10 22:33:19.000000". The below is the vanilla rails way.
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :size=>"20" %>
</div>
How can I simply apply a format? I tried various approaches, for example strftime should work, I thought. But when I try the following, I get an error undefined method 'strftime' for nil:NilClass
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :value=>f.object.birth_date.strftime('%m/%d/%Y'), :size=>"20" %>
</div>
Based on some other questions/answers, I tried the following. It works for non-null values, but it is ugly code, and it doesn't work for blank values (actually it shows today's date).
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :value=> Time.parse(f.object.birth_date.to_s).strftime('%m/%d/%Y'), :size=>"20" %>
</div>
In playing around, it seems that outputting f.object.birth_date is treated as a date, rather than datetime. However, when displayed in the text_field (original, ugly formatting), it includes the time. It is friday afternoon, and my combined lack of familiarity with rails forms and ruby date/time objects is making me feel foolish.
Any simple way to get my form to display nothing if null/blank, and a friendly date otherwise?
If you want a blank string if birth_date is empty, you should simply check that birth_date is non-nil beforehand:
<%= f.text_field :birth_date, :value => (f.object.birth_date.strftime('%m/%d/%Y') if f.object.birth_date), :size => "20" %>
This way, when birth_date is nil, :value gets set to nil.
Have you tried using the date_select form builder helper method? You can also use datetime_select, but it looks like you just want to work with the date here.
<div class="field">
<%= f.label :birth_date %>
<%= f.date_select :birth_date %>
</div>
The API docs are here: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select
Add on the options you need.
I've always used that approach, or a javascript date selector like this one from jQuery UI. There are plugins for most JS frameworks these days.
If it MUST be a text_field, use a human language date parsing library like chronic. It'll work, but will require that you parse the input from the form somewhere before applying the attribute to your object.

Resources