I have added activity_logs to my application and I show #activities based on giving param_date to url.
My link/path looks like:
http://localhost:3000/users/activity_logs?param_date=2016-09-12.
I do much like to add Next day & Previous day on same page. How can I find the Next day & Previous day based on the date I have on param_date.
Ex: = link_to 'Next day', activity_logs_path(param_date: date)
So basically if param_date is 2016-09-30, Next Day would be: 2016-10-01 and Prev day: 2016-09-29
try this:
prev_data = (Date.parse(params[:param_date]) -1).strftime('%F')
next_data = (Date.parse(params[:param_date]) +1).strftime('%F')
Ruby's date class has a next_day and a prev_day method:
Just parse the date from the params in your controller
#date = Date.parse(params[:param_date])
and build the links like this in your views
link_to('Next day', activity_logs_path(param_date: #date.next_day))
link_to('Previous day', activity_logs_path(param_date: #date.prev_day))
Related
I have a form which allows user to select date, in the view i have it so the user only selects the year, but when the date is saved, it saves todays day and month along with it? all I want it to display is the year, which the user selects, this is my code:
<%= f.date_select :finishdate, :order => [:year] %><br>
If you wish to show only the year value in the form and store it in the database without the month and day, then you can have an integer field and only show the year value as follows:
<%= f.select :finishdate,Date.today.year-10 .. Date.today.year+10 %>
you can try
<%= f.select_year :finishdate, :order => [:year] %><br>
What is the end result that you'd like to work with? If it is only the year, you'll probably not want to use the date_select as that, I believe, will return a DateTime instance and not just the year.
If you do need just the year, you can look into other helpers like select_year.
Im having an issue sorting an array by the current date.
my database has a field called day
day has the days of the week eg: Monday, Tuesday, etc.
I am trying to sort my index view page by the current day.
I would like to do somehting like this in my controller,
#happies = Happy.where(id: #search.results.map(&:id))
.page(params[:page])
.where(:day => Date.today.strftime('%A').capitalize.to_s)
but instead of returning only happies with the day Monday I would want to order by day where day is equal to the current day.
I also thought about doing this in my view
with something like
<% #happies.sort_by(:day => Date.today.strftime('%A').capitalize.to_s).each do |happy| %>
the above does not work but im trying to get accross what I wan to achieve. Any ideas on how to implement this?
Maybe there is an activeview helper?
If you were not paginating, you could sort the results in plain ruby like this:
day_order = %w(Tuesday Wednesday Thursday Friday Saturday Sunday Monday)
#happies = #happies.sort_by{|happy| day_order.index(happy.day)}
sort_by takes a block that returns the value to sort by.
However, you appear to be paginating using will_paginate. That's fine but it makes things more complicated.
The pagination necessarily happens in the database via limit and offset (so as to avoid returning the entire contents of the table to the Rails process). Therefore you want the sorting to also happen in the database. If you were to sort in ruby (as above) you would be sorting after pagination, meaning the first page would give you essentially random results, and then you'd sort them. Probably not what you want.
Long story short, you probably want to use order instead of sort_by, and I'm going to have to dip into SQL for this one:
#happies = Happy.where(id: #search.results.map(&:id))
.page(params[:page])
.order("CASE day WHEN 'Tuesday' THEN 0 " \
"WHEN 'Wednesday' THEN 1 " \
"WHEN 'Thursday' THEN 2 " \
"WHEN 'Friday' THEN 3 " \
"WHEN 'Saturday' THEN 4 " \
"WHEN 'Sunday' THEN 5 " \
"WHEN 'Monday' THEN 6 END")
If you want to avoid SQL, perhaps it is possible to use Arel for this, I'm not sure.
Edit
I see now you want to start with the current day, i.e. not hardcoded as Tuesday like I did. To fix my SQL version - and borrowing a bit from #Snarf's answer - you could do this:
days = %w(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
days.rotate!(days.index(Time.zone.now.strftime("%A")))
case_pieces = days.each_with_index.map do |day, i|
"WHEN '#{day}' THEN #{i}"
end
#happies = Happy.where(id: #search.results.map(&:id))
.page(params[:page])
.order("CASE day #{case_pieces.join(' ')} END")
Another thought
If I was writing the app myself, I would be tempted to store the day as an integer from 0 to 6, instead of as a string. Then you could order using the modulo operator, something like this:
days = %w(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
day_offset = days.index(Time.zone.now.strftime("%A"))
#happies = Happy.where(id: #search.results.map(&:id))
.page(params[:page])
.order("(day - #{day_offset} + 7) % 7")
Here's a pure ruby solution.
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
days.rotate(days.index(Time.now.strftime("%A")))
#=> ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
Basically the same as #Snarf - this is only ruby and will not support pagination
today = Date.current.strftime('%A')
# => Monday
days = Date::DAYNAMES
# => ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
today_index = days.index(today)
# => 1
#ordered_days = days.rotate(today_index)
# => ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
#happies = Happy.where(id: #search.results)
<!-- view -->
<% #ordered_days.each do |day| %>
<!-- in memory selection from the #happies collection, could be emtpy -->
<% occurring_on = #happies.select { |happy| happy.day == day } %>
<%= day %>
<% occuring_on.each do |happy| %>
<%= happy %>
<% end %>
<% end %>
In the month view, I click on the date, and then the view changes to the day view. When I click on the new event link, I would like the start date to be that of the day selected instead of the default of today's date.
If today is March 12, 2013, and I want to create an event on March 28,2013, I'll click on the day cell for March 28 in the month view. The day view for March 28 will come up. I will click the new event, and the start time for the event will be March 12, 2013 (whatever current day is, is shown) and I'll need to manually select March 28, 2013 (or whatever day I want).
I figured out the way to hard-code it, but this isn't going to work in production. Is there a way to dynamically pass the selected days's start date so that it's automatically set for any day of month is selected?
Here's the dayClick code:
dayClick: (date, allDay, jsEvent, view) ->
if (allDay)
# clicked entire day
$('#calendar')
.fullCalendar('changeView', 'agendaDay')
.fullCalendar('gotoDate', date.getFullYear(), date.getMonth(), date.getDate())
do I use the select method? if so how? I don't understand the doc http://arshaw.com/fullcalendar/docs/selection/select_method/
http://arshaw.com/fullcalendar/docs/selection/select_callback/
In the events.js.coffee, I'm attempting to dynamically create a new event link in the :
$('#new-event').append("<a>custom link built thru js</a>").attr('href', 'events/new?starts_at=2013-03-28') <-- How to set starts_at by obtaining the date from day selected dynamically? Use calendar's select method to obtain the date parameters?
How are the parameters for the selected date from dayClick passed in? Or do I obtain this info from the gotoDate?
EventsController.rb:
# GET /events/new
# GET /events/new.json
def new
#event = Event.new
#event.starts_at = (params[:starts_at]) # sets the date
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #event }
end
end
Event.rb model:
def as_json(options = {})
{
:id => self.id,
:title => self.title,
:description => self.description || "",
:start => starts_at,
:end => ends_at,
:allDay => self.all_day,
:recurring => false,
:url => Rails.application.routes.url_helpers.event_path(id),
:type_of => self.type_of
}
end
views/calendar/show.html.erb:
<%= link_to "new event", controller: "events",
action: "new",
starts_at: "28-03-2013" %> This will set the starts_at param manually via Rails. How do I obtain this dynamically? Using jQuery see code above in to create link that has the starts_at parameter (see code above).
I'm not sure if this is the best solution, but here's how I got it to work. In the events.js.coffee:
$('#calendar').fullCalendar
dayClick: (date, allDay, jsEvent, view) ->
if (allDay)
# clicked entire day
$('#calendar')
.fullCalendar('changeView', 'agendaDay')
.fullCalendar('gotoDate', date.getFullYear(), date.getMonth(), date.getDate())
$('#new-event').append("<a>custom link built thru js</a>").attr( 'href', 'events/new?starts_at=' + date )
How to convert date in format 09-feb-73 to 02/09/1973 (mm/dd/yyyy) using Ruby on Rails?
Valid Ruby datetime formats
Date.strptime("09-feb-73", "%d-%b-%y").strftime("%m/%d/%Y")
Note that strptime is a part of Rails. And these are the relevant formats used:
%b - The abbreviated month name (``Jan'')
%d - Day of the month (01..31)
%m - Month of the year (01..12)
%y - Year without a century (00..99)
%Y - Year with century
You can do it with Date.parse and Date#strftime:
d = Date.parse('09-feb-73').strftime('%m/%d/%Y')
# "02/09/1973"
You could also use Date.strptime instead of Date.parse:
d = Date.strptime('09-feb-73', '%d-%b-%y').strftime('%m/%d/%Y')
# "02/09/1973"
The advantage of strptime is that you can specify the format rather than leaving it to parse to guess.
Date.strptime("09-feb-73", "%d-%b-%y").strftime("%m/%d/%Y")
Date Formats: http://snippets.dzone.com/posts/show/2255
If you require this in a view, I would suggest using localizations, since you can easily change the behavior based on your user's local settings and keep your controller code tidy (why should the controller care about the date format?). Example:
# config/locales/en.yml
en:
time:
formats:
short: "%m/%d/%Y"
# view file
<%=l Time.now, :format => :short %>
For more information on rails localizations, see the Rails Guide.
all,
Am new to RoR and hence needed some guidance w.r.t Date field.
Background:
1 > I create a model object using rails generate scaffold <Model> name:string remainderDate: date
2 > Now when I have deployed the model to DB using rake db:migrate and on opening the URL: localhost:3000/<Model>s/new, the displayed date field is in the format YYYY MM DD, all 3 separate fields with dropdown with
YYYY values >=2006 and <=2016
MM values >= January and <= December (obvious)
DD values >= 1 and <=31
Question 1:
1> Where is the code for setting the values to these fields?
2> Can I change the format to MM DD YYYY?
3> Can I restrict the values being added to the list? i.e. for the current year 2011, only months starting from April should be shown and only dates starting current day should be shown
4> Where can I change the display text for the new form? I opened up new.html.erb and could not understand where the display text is set. I also opened up _form.html.erb and could not locate where necessary changes can be done?
Take a look at the syntax for date_select:
http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select
In your form you would have something like this:
<%= f.date_select :remainderDate, {:order => [:month, :day, :year],:prompt => true, :start_year => Time.now.year, :end_year => 2016} %>
So answers to your quenstions:
1/ as Wes answered
2/ the :order option in my example
3/ your can only restrict the year, not the months or dates with the options as you see with start_year and end_year in the example. You coud restrict further using validations in your model.
4/ what exactly do you mean with "the display text for the new form"? Do you mean the display text for the date field? That would be next to the <%= f.label %>
Regarding formats of the date field you want to pass the string in the way rails already is because mysql accepts it without modification. That said you can certainly change how the user enters the data on the form for a new record. Look for the view code in
app/views/<model>/_form.html.erb