Datetime format date received is in different format in rails - ruby-on-rails

I have a table which contains a column named DOB whose data type is DATETIME.The problem is that created_at is also a datetime but its data received through JSON is in this format
"created_at":"2013-02-02 11:57:42",
"dob":"2013-02-18T18:30:00Z"
Both the dates are in different format but both of them has datetime data type.
Now I'm using Datejs
to format the date which will not parse DOB format it can only parse created_at format.
What should I do now ?
Here's what I'm doing to parse through datejs
if(value.dob != null){
alert(value.dob);
d1 = Date.parse(value.dob);
alert(d1);
dob = d1.toString("M-d-yyyy");
}
And I'm getting this error on console:
: d1 is null
[Break On This Error]
dob = d1.toString("M-d-yyyy");
My controller:
def get_oi_report_contact
#contactlist = CaseOiReportMap.select("rc.*").where("case_oi_report_maps.oireport_identifier = ?",identifier)
.joins("LEFT JOIN case_oi_report_contacts_maps cm on cm.case_oi_report_map_id = case_oi_report_maps.id")
.joins("LEFT JOIN oi_report_contacts rc on rc.id = cm.oi_report_contact_id ")
respond_to do |format|
format.json { render :json => #contactlist.to_json }
end
end
I have also used monkey patch:
class ActiveSupport::TimeWithZone
def as_json(options = {})
strftime('%Y-%m-%d %H:%M:%S')
end
end
But it doesn't seem to work.

Use strftime to format the time string http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html#method-i-strftime

Related

Check whether a string contains numbers

I have input values like:
string = "devid"
string = "devid123"
string = "devid.123.devid"
I need to sort strings that contain .(number)., for example "devid.123.devid". How can I separate only strings that consist of .(numbers). like .123.? Help me find a solution.
In a controller, I have:
#person = Person.new
personname = params['personname']
if personname.match("/\d+/")
#person.person_name = personname
#person.save()
result = 'true'
end
When I execute this code, I get "devid123" and "devid.123.devid".
If its certain that the format of the valid personname is always
<string>.<number>.<string>
You can try using :[regex, index] method for strings in ruby.
https://ruby-doc.org/core-2.6.1/String.html#method-i-5B-5D
So if
personname = "devid.123.devid"
s[/(.*)(\.\d+\.)(.*)/, 2] = ".123."
There are three different groups in the regex (.*)(\.\d+\.)(.*).
Matches anything
Matches a .<number>.
Matches anything
So based on this regex, the second group should provide you .<number>. which, I hope, is what you need.
Tested with Ruby 2.4.1
If I understand this correctly you only want a string where the digits are preceded by .. If so you need to modify your regex to be /\.\d+/
#person = Person.new
personname=params['personname']
if personname.match("/\.\d+/")
#person.person_name = personname
#person.save
result = 'true'
end
But this sounds like logic you should be handling in the model, since this is tagged as rails and not plain old ruby
controller
class PersonController
def create
if #person = Person.create(params)
result = 'true'
else
result = 'false'
end
# whatever you doing with result
end
end
person.rb
class Person < ApplicationRecord
validates :personname, format: { with: /\.\d+\./, message: 'must include digits' }
end
You can play with the regex # rubular

How to convert data into an Excel file

I am using the CSV class to convert data into an Excel file based on http://railscasts.com/episodes/362-exporting-csv-and-excel.
Upon downloading the Excel file it is not updated with the latest data which I see on my webpage using filters. My Excel file contains data which is being shown when the page first loads.
I tried to debug the problem and tried other gems like xlsx_writer, getting the same result:
def commission_report
today = Date.today
if params[:from_date].present?
from_date = params[:from_date]
to_date = params[:to_date]
elsif params[:filter] == 'monthly'
to_date = today
from_date = today - 30
else
to_date = today
from_date = today - 7
end
#commissions_report = UserOrderHistory.select("user_order_histories.*,SUM(user_order_histories.revenue_sharing) as revenue_total, restaurants.restaurant_name, managers.username,revenue_sharings.revenue").joins("LEFT JOIN revenue_sharings ON revenue_sharings.restaurant_id = user_order_histories.restaurant_id").joins("LEFT JOIN restaurants ON restaurants.id = user_order_histories.restaurant_id").joins("LEFT JOIN managers ON managers.id = restaurants.manager_id").where("user_order_histories.status != ''").where("revenue_sharing > 0").group("user_order_histories.restaurant_id,user_order_histories.deduction_date").where("user_order_histories.deduction_date BETWEEN ? AND ?",from_date,to_date).order(sort_column + " " + sort_direction)
#commissions_report = #commissions_report.as_json
#commissions_report = Kaminari.paginate_array(#commissions_report).page(params[:page]).per(10)
# raise #commissions.inspect
respond_to do |format|
format.html
format.csv { send_data #commissions_report.to_csv }
format.xls #{ send_data #commissions_report.to_csv(col_sep: "\t") }
end
end
When you're making the filtered request to download the CSV, the params are not being parsed:
<%= link_to 'Download CSV', your_path(from_date: params[:from_date], to_date: params[:to_date], filter: params[:filter]) %>
This way your params will get sent back again to your controller.
It's because when you click on:
link_to "CSV", products_path(format: "csv")
It goes to the index method in the products controllers and within that method you're again fetching all the records from the DB:
#products = Product.order(:name)
So all you've to do is pass the collection of filtered products to the CSV format respond. Something like this:
format.csv { send_data #filtered_products.to_csv }

Filter data in JSON string

I have a JSON string as pulled from some API
[{"_id"=>"56aefb3b653762000b400000",
"checkout_started_at"=>"2016-02-01T07:32:09.120+01:00",
"created_at"=>"2016-02-01T07:29:15.695+01:00", ...}]
I want to filter data in this string based on created_at, e.g. letting the user chose a specific date-range and then only show the data from this range.
E.g.
#output = my_json.where(created_at: start_date..end_date)
My first thought was to somehow transfer the JSON string to Hashie, to interact with JSON as the data were objects:
my_json = (my_json).map { |hash| Hashie::Mash.new(hash) }
but that didn't work out
undefined method `where' for Array:0x007fd0bdeb84e0
How can I filter out data from a JSON string based on specific criteria or even SQL queries?
This simplest possible way would be to use Enumberable#select directly on the array of hashes:
require 'time'
myjson.select { |o| Time.iso8601(o["created_at"]).between?(start_date, end_date) }
If you want a fancy interface surrounding the raw data:
require 'time' # not needed in rails
class Order < Hashie::Mash
include Hashie::Extensions::Coercion
coerce_key :created_at, ->(v) do
return Time.iso8601(v)
end
end
class OrderCollection
def initialize(json)
#storage = json.map { |j| Order.new(j) }
end
def between(min, max)
#storage.select { |t| t.created_at.between?(min, max) }
end
end
orders = OrderCollection.new(myjson)
orders.between(Time.yesterday, Time.now)

rails - how to show and save a date in us format?

I can get my content_date to show in mm/dd/yyyy format and I can save it correctly.
If I have a validation error in other data the form redisplays the date the desired way which is mm/dd/yyyy
I can also edit a record and see the date in format mm/dd/yy
The problem I have is that editing the record flips the month and year so that
08/02/2012
becomes
02/08/2012
and
08/19/2012
doesn't work at all.
Ironically If I record the record twice in a row and the day is not more than 12 it flips back to the original value
View:
= f.text_field :content_date, id: 'datepicker', size: 10
I got new and create to work with (links controller)
def new
#link = Link.new
#link.content_date=Time.new().strftime("%m/%d/%Y")
...
def edit
#link = Link.find(params[:id])
#link.content_date=Time.new().strftime("%m/%d/%Y") if #link.content_date.nil?
def create
#link = Link.new(link_params)
if #link.content_date.nil?
#link.content_date = Time.new().strftime("%Y/%m/%d")
else
#link.content_date = #link.content_date.strftime("%Y/%m/%d")
end
but update (rails 4.0.2) is now just
def update
redirect_to Link.find(params[:id]).tap { |link|
link.update!(link_params)
}
end
and I can't figure out how to change the :content_date in the update the way I did in the create
fyi I have the american_date gem in my Gemfile but it doesn't help (and doesn't help if I remove it either).
I don't currently have any date initializer in config/initializers/
js date picker:
$ cat app/assets/javascripts/date-picker.js
$(function() {
$( "#datepicker" ).datepicker();
});
$(function(){
var dateInput = $("#datepicker");
var format = 'yy-mm-dd';
dateInput.datepicker({dateFormat: format});
dateInput.datepicker('setDate', $.datepicker.parseDate(format, dateInput.val()));
});
I changed
/app/assets/javascripts/datepicker.js
changing
var format = 'yy-mm-dd';
to
var format = 'mm/dd/yyyy';
Then I added a file config/inititlaizers/date-format.js, with
# Date
# ----------------------------
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
# DateTime
# ----------------------------
DateTime::DATE_FORMATS[:default] = "%m/%d/%Y"
# Time
# ----------------------------
Time::DATE_FORMATS[:default] = "%m/%d/%Y %H:%M:%S"
This helped in all the displays and input fields and date-picker but the date still flipped.
Finally (this bit fixes the date flipping part), I changed my controller to be:
def update
r = Link.find(params[:id])
r.tap { |link|
link.update!(link_params)
}
r.update!(:content_date => link_params[:content_date].to_date.strftime("%Y-%d-%m"))
redirect_to r
end

Rails: Attempting to query created_at

I have the following action in my controller:
def find_by_registration_date
#registration_date = params[:registration_date]
#registrations = Registration.where(:created_at => #registration_date)
end
...were params[:registration_date] is a simple date (no time) like:
"registration_date"=>"2014-07-16"
...and my created_at date looks like...
created_at: "2014-07-16 15:50:52"
How can a search based on Y-M-D?
If its mysql, you can do
#registrations = Registration.where("DATE(created_at) = ? ", #registration_date)
For other databases, find the equivalent date function

Resources