rails date ranges for same date - ruby-on-rails

Query below works fine when user selects different dates but when user selects same dates like 3/5/2011 and 3/5/2011 it returns nothings. How can i handle this ? If user selects same dates, i want it to find clients which are created at that date.
Client.where(:created_at => date_from..date_to)

You may need to modify your query as below to get between beginning_of_day and end_of_day
Client.where(:created_at => date_from.beginning_of_day..date_to.end_of_day)

You could create a helper method:
def date_range(from, to)
from == to ? from : from..to
end
Client.where(:created_at=>date_range(date_from,date_to))

Related

Sign in count per day in Devise

Is there any way to find out how many unique logins per day a user has?
We can track a user to find out how many sign_in's or when the user signed in with:
User.last.sign_in_count
or
User.last.last_sign_in_at
But not how many time he logged in each day.
Here is what I did in my rails app:
I created a new model to track each visit
rails g model Visit user_id:integer user_ip:inet user_email:string
Then
rake db:migrate
Next I created a controller to track sessions with
app/controllers/track_sessions_controller.rb
info about devise session controller
Then I added code to run after each successful login
class TrackSessionsController < Devise::SessionsController
after_filter :after_login, :only => :create
def after_login
Visit.create!(user_id: current_user.id, user_ip: current_user.current_sign_in_ip, user_email: current_user.email)
end
end
Then update this section of your routes.rb
devise_for :users
to
devise_for :users, :controllers => { :sessions => "track_sessions" }
If you wanted to see how many unique logins per day a user has, you can now do something like this:
User.all.each do |user|
logins_per_day(user.id)
end
def logins_per_day(user_id)
dates_visited = Visit.where(user_id: user_id).select('distinct created_at').all.collect{|x| x[:created_at].to_date}
puts "************* USER ID #{user_id} *************"
dates_visited.group_by {|date| date}.map {|date_visited, times_visited| puts "Date Visited: #{date_visited} Times Visited: #{times_visited.count}"}
end
what you can do is create a table that will work like a log, there you input every login, or, what you can do is, create a .txt at yor soucer code that get de login after they pass the login control and insert to the .txt username and date, but the bad side is the log will be at the computer.
if you choose use a tablein sql, acces or whatever you wanna, just one select solve.
select count(*) from table_log_login where user = 'user' and date = 'yyyy-mm-dd';
I'm having trouble understanding what you want, so:
If you want to count the number of logins per day, you can create an after filter for the login method where you check the date (this is assuming you have a table where you track the number of logins with a date).
If you want to know the number of consecutive days your user is logging in, you can do the same but instead save a start date, and an end date, so you know when the "streak" will be over.
PS: if you have trouble with english, post both in english and any other language you're fluent in, so someone can properly translate.
Ok, sorry, i understand well but dont write so good, than lets try in two languages.
When you log in at your program, you insert at log table in a database and when the program close, update the row, insert with login start and update with login end, you can use smalldatetime in sqlserver or datetime in mysql, so, you can select without problem the day, hour or minute of logins.
think it:
insert into tb_login(cod_login, cd_user, dt_start) values('26','5','2013-12-30 08:02');
note: you need have a columns that accept null, the columns is " dt_end "
than you update
update set dt_end = '2013-12-30 10:10' from tb_login where cod_login = '26';

Rails collection of current + past 30 days

So I've got a collection called #events and I am defining it as
#organization.owned_events.current.reverse
However, what I would actually like to do is have not actually current, but anything current or expired in the last 30 days. I tried
#organization.owned_events.current-30.days.reverse
But this just provided an empty collection. I think this is because what I actually want is not current-30.days, but actually current AND current-30.days
Not sure how to write that though. Can I somehow define another term instead of current like net_thirty and make that equal current or within last 30 days?
In your event model you can do:
scope :from, ->(duration){ where('your_datetime_field_here > ?', Time.zone.now - duration ) }
Since you want to filter by a date or datetime field, previous option is for a datetime field, if you want to filter by a date field:
scope :from, ->(duration){ where('your_date_field_here > ?', Time.zone.today - duration ) }
->(){} is a block you are passing to the scope.
You would use these scopes like this:
any_events.from(30.days)
In your case:
#organization.owned_events.from(30.days)
You could also want to filter events not after today:
scope :from, ->(duration){ where('your_date_field_here BETWEEN ? AND ? ', Time.zone.today - duration, Time.zone.today ) }

How compare time range using created_at fields on rails

I need to get the records only included on time range using default created_at Rails field. No matters the day was created.
I have this:
#start_time = test.start_time.strftime("%I:%M%p")
#end_time test.end_time.strftime("%I:%M%p")
#websites = device.websites.where(:created_at => #start_time..#end_time)
I was searching for something like this:
#websites = device.websites.where(:created_at::time => #start_time..#end_time)
This generate this SQL sentence without results.
SELECT DISTINCT `websites`.* FROM `websites` WHERE `websites`.`device_id` = 2 AND (`websites`.`created_at` BETWEEN '16:10:00' AND '21:10:00')
But if I add time function to created_at field, works fine.
SELECT DISTINCT `websites`.* FROM `websites` WHERE `websites`.`device_id` = 2 AND (time(`websites`.`created_at`) BETWEEN '16:10:00' AND '21:10:00')
How is the best Rails way to do this ?
Rails automatically converts the time objects to the format that your database requires, so there is no need for strftime. You should be able to do it like this:
#websites = device.websites.where(:created_at => test.start_time..test.end_time)

Supporting timezones in a Rails application

I added a calendar to my rails application. We have events with a start date and an end date (both includes hours and minutes). This ones are fields in the events table, actually their format is datetime. When you select the start date, end date, title and description (among others) for an specific event the the parameters hash is something like this:
parameters = {"event" => {"title" => "a title", "description" => "a description", "start_date" => "2012-09-23 23:45", "end_date" => "2012-09-24 15:32"}}
In the events controller i have something like this:
Event.create(:title => params[:event][:title],
:description => params[:event][:description],
:start_date => params[:event][:start_date].present? ? DateTime.strptime(params[:event][:start_date], "%Y-%m-%d %H:%M") : nil,
:end_date => params[:event][:end_date].present? ? DateTime.strptime(params[:event][:end_date], "%Y-%m-%d %H:%M") : nil,
...
)
Well, when this event is stored into the database (mysql) the value for start date is "2012-09-23 20:45" while the value for end date is "2012-09-24 12:32". I understand that Rails is automatically dealing with timezones. My problem is that when I want to fetch all the events for a specific time (for example, all events that occurs today) I do:
query = "((start_date between ? AND ?) OR (end_date between ? AND ?))"
query << "title NOT LIKE ? AND ..."
self.events.where(query,
Time.now.beginning_of_day, Time.now.end_of_day,
Time.now.beginning_of_day, Time.now.end_of_day,
some_restriction_here, ...)
I get the wrong events! (it is obvious why, the date and time is different in the database from the inputs). There's and obvious solution also, bring all the events into memory and the date and time will be as the original again but this is expensive in terms of resources. By the other hand this don't solve the problem of timezones, if someone in china crate an event the value in the database will be relative to the time offset of the server localization. I could have a field somewhere where the user can set a time zone and work with this storing a specific date for such user and working through this, what is your suggestion about the best way to deal with this?
Rails stores all dates in database in the UTC format. So one way is to always do operations in UTC and in the view convert the displayed dates to current time zone. The other way is to change Rails timezone on the beginning of every action. All parsed times and dates will then be in your custom time zone.
def action_name
Time.zone = "Prague"
# ... logic
end

Ruby on Rails - Date Comparison

I am trying to compare dates for an app in rails. I have tried this link Comparing dates in rails. But this is not what I want, suppose I have a filter according to dates, then I am doing
<% jobs = #user.jobs.where(:curr_date => (Date.today))%>
Here, curr_date is a "date" attribute chosen by me.
This code works for entries which have today's date, but if I want all entries which have date between today and a week before, what should I do?
Thanx! :)
You can simply use
jobs = #user.jobs.where(:curr_date => (DateTime.now..1.week.ago))
Updated to DateTime.now or you can also use Date.today.to_time otherwise there will be an error for comparing a Date and a Time
I think something like that should work:
<% jobs = #user.jobs.where(['curr_date < ? AND curr_date > ?', Date.today, 1.week.ago])) %>
comparison_date_1 <=> comparison_date_2 might be useful to to you which returns -1,1,0 accordingly and you can populate them......
Haven't tried this in a console but I think it should work:
# You need to implement the #week_before method
#user.jobs.where(:curr_date => (Date.week_before..Date.today))
Active Record Querying - Array Conditions Check under Range conditions (2.2.2)

Resources