Rails 3 Need help with next month on a calendar - ruby-on-rails-3

is it possible to advance a variable something like #current_month = Date.today.month+1 then forward it back to the index page, if so how

#current_month = Date.today + 1.month
Not sure quite what you mean by 'forward it back to the index page', but if you then
render :action => 'index'
the #current_month instance variable will be available to the index view of that controller. You could print out the month only by using strftime, eg <%= #current_month.strftime("%B") %>
Check out .strftime at http://www.ruby-doc.org/core/classes/Time.html#M000392

For calendar operations, one probably wants to start at the beginning of the month.
#current_month = 1.month.from_now.beginning_of_month
This will return a ActiveSupport::TimeWithZone object which is similar to Ruby's DateTime.
OR
#current_month = Date.today.at_beginning_of_month.next_month
which will return a Ruby Date object.

Related

Ruby on Rails: Creating a Calendar, get the next week (redirect loop)

I'm creating a Calendar to view of a week without the Calendar gem. (It will get pretty specific past the use of that gem).
When I render a view to see a page (index) it will display the dates and days for that particular week. How can I make a button that is clickable that will change those dates to the previous week or the next week?
I'm confused on how to do it, and am looking for coding suggestions of course. How I have attempted this so far is I have created two helper functions to add the days to my current variables. Then I want to display the same page after the helper function updates to the next week or previous week.
Here is how I am calling my helper function
<%= link_to '<', week_ahead, class: 'month-arrow' %>
def week_ahead
#viewDate = #viewDate + 7.days
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
helper_method :week_ahead
def week_back
#viewDate = #viewDate - 7.days
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
helper_method :week_back
Here is what I am using in my controller
def index
#user = User.find(session[:user_id])
#viewDate = Date.today
#weekStart = #viewDate.beginning_of_week(start_day = :monday)
end
If I put a redirect_to user_path command in the helper function it gives a redirect loop. I still want my view to update to the next week when they click on the "next arrow".
Use simple calender gem. It is really helperful.https://github.com/excid3/simple_calendar

Refactoring Ruby on Rails link_to with sorting

I'm very new to Rails, Databases, and web development in general, right now my feature is working but I'm 100% sure it's not the cleanest or most Ruby-esq way of doing it. Basically I want to use two separate links that sort the same table by different columns, without using two controller actions and two views. I'd rather just user the one index action that takes a parameter indicating how to sort the returned data.
Current Controller:
Controller
def index
#casinos = Casino.order('name ASC')
end
def casinos_by_region
#casinos = Casino.order('location ASC')
end
And links in the view
%h3 Sort by:
= link_to 'Name', casinos_path
%br
= link_to 'Location', casinos_by_region_path
I read the docs but I didn't see an obvious way on passing an argument from the view to controller using a link_to path? I know I could do it other ways, but I refuse to believe I can't do it this way. Sorry for the dumb question!
Thumbs up to CDub. Just to enhance it, you might want to add a little safety to the sorting by assuring the params[:sort_param] contains an expected value in case someone decides to key in the url. The code below not only assures you've got an acceptable sorting key but also provides a default value for the first visit to the url.
def index
params[:sort_param] = %w{name location}.include?(params[:sort_param]) ? params[:sort_param] : 'name'
#casinos = Casino.order "#{params[:sort_param]} ASC"
end
How about this:
def index
#casinos = Casino.order("#{params[:sort_param]} ASC")
end
%h3 Sort by:
= link_to 'Name', casinos_path(:sort_param => "name")
%br
= link_to 'Location', casinos_path(:sort_param => "location")
The path in link_to can take a hash which are parameters on the request. You can set a parameter (in this case sort_param) with what value you want to sort by, then use that in your order on the index method of the controller.

Date and Date Ranges in Rails 3

I have a Rails 3 application with a prescription model. The model has a number of fields, two of them are to calculate and display the duration of a prescription.
At the moment the user enters a value in a text field such as '3 Months' and then manually changes a datetime input to three months from now. This seems like a perfect form to automate for the user.
Currently the fields are like this:
Duration of Treatment
<%= f.text_field :duration, :class => "input-text" %>
Date of Expiry
<%= f.datetime_select :expiry, :order => [:day, :month, :year], :class => "input-text" %>
So, my question. How can I create two dropdown lists for the duration field such as:
[1] [Day]
The user can select the number from the first list and in the second they can choose Day, Week or Month.
The value they pick using the duration select boxes would be saved as a text string e.g. "1 month" and the value of the Time.now in 1 month would be saved as a datetime value in the expiry column.
Is something like this possible to do? If so, how?
I'll provide an example of how you'd use the chronic gem, since it seems tailor-made for this purpose:
require 'chronic'
duration = "3 months" # => "3 months"
Time.now # => 2012-07-09 18:43:50 -0700
Chronic.parse(duration + " from now") # => 2012-10-09 18:43:55 -0700
If I understand your use case correctly, you can then just get rid of the datetime select entirely. Ask the user for the text duration and assign that to the text attribute. Then use chronic to determine the time value from the text parameter and assign that to the datetime attribute. For extra credit get the parsed time value asynchronously and display it on the page before they submit the form so they can see that what they are submitting makes sense.
You can just do something easy like:
Time.now + 10.days
Source: How to add 10 days to current time in Rails
And how to do drop-downs?
Drop down box in Rails
Assuming the prescription is valid at the time of object creation, you can store the start date in the database as the current time Time.now (may want to convert to a datetime) and then based on the drop-down, add the amount of time until it expires like off the top of my head:
eval "Time.now + #{params[:prescription][:amount].#{params[:prescription][:time_type]}"
Hope that made sense. I would look up a better way to add the time though that maybe doesn't use eval. Heres the time reference: http://api.rubyonrails.org/classes/Time.html
First, change your duration field to a select menu with 1-30, or whatever numbers you want.
Then in the controller action that handles your form:
#prescription = Prescription.new(params[:prescrption])
#prescription.duration = "#{pluralize(params[:prescription][:duration], params[:prescription][:expiry])}"
if params[:prescription][:expiry] == "Day"
#prescription.expiry = Time.now + params[:prescription][:duration].days
elsif params[:prescription][:expiry] == "Week"
# Put week logic here
elsif params[:prescription][:expiry] == "Month"
# Put month logic here
end
# Put the rest of the #prescription.save stuff here.
It's a little verbose, but I think that's kind of the way it is with the way time is set up in Ruby...

RoR, Passing a variable into view gives a null object

I am setting a variable in my controller but for some reason it is not getting set. I tried it two ways.
def update
# #available_cars = Car_info.where("user_id = ?", session[:user_id])
#available_cars = Car_info.find_by_user_id(session[:user_id])
end
In my view I do this.
<% #available_cars.each do |car| %>
<%= car.name %>
<% end %>
What I intend to do is populate the #available_cars into a drop down list but I can't even get them to print. I know the session[:user_id] is set because I print it and access it elsewhere.
I get this error...
Expected D:/RailsProjects/mileage/app/models/car_info.rb to define Car_info
in my controller
app/controllers/active_car_controller.rb:6:in `update'
Any help would be appreciated. New to RoR.
I see your controller method is named 'udpate' instead of 'update' - could that be your problem?
You need to change your query to:
#available_cars = Car_info.find_all_by_user_id(session[:user_id])
The find_all part will get you all records, whereas find only gets you the first. Another way to write this is:
#available_cars = Car_info.where("user_id = ?", session[:user_id])
Ideally, you want your class to be called CarInfo, not Car_info.

Rails 3 can't get beginning_of_week

Have a publish_on datetime field.
Just trying to get to the begining_of_week from the publish_on.
Tried a helper
def start_week(publish_on)
DateTime.parse(publish_on).beginning_of_week
end
and in view <%= start_week(#survey.publish_on) %>
Tried in my model
def set_start_week
publish_on.beginning_of_week
end
Hell, even tried this helper
def this_should_work
DateTime.now.beginning_of_week
end
But everything returns a invalid date to my view. It works in irb, why not in my view?
EDIT
module SurveysHelper
require 'date'
require 'time'
def this_should_work
DateTime.now.beginning_of_week
end
end
take_survey.html.erb
<%= this_should_work %>
Error
invalid date
I encountered the same problem when trying to use ActiveSupport outside of Rails. I found the answer here:
http://guides.rubyonrails.org/active_support_core_extensions.html
Here is the key bit:
require 'active_support/all'
Have you customized your rails stack to no longer include ActiveSupport?
In rails 3.0.9 I got
undefined method `at_beginning_of_week'
wherever I put it, my alternative solution is:
def SomeMethodPutAnywhere
...
#datey = Date.today
#monday = #datey - #datey.wday + 1
##monday is now the monday of the current week.
#Remove the constant '+1' if your week begins sunday...
...
end