Current year displayed in the coming years - ruby-on-rails

In my application a user can fill in a form to create learning goals for the classes they take each semester at school. This application should guide them through their full 4 years of their study.
In my form I've included
<p><%= Time.now.year %>/<%= Time.now.year + 1 %></p>
to get the current schoolyear. In the index of their learning goals is a table which lists the schoolyear in which their goals were created.
How do I get it to show 2013/2014 (the schoolyear in which it was created) when it's, for example, the year 2015?

If each goal has a created_at field, it should be as simple as using this for each goal:
<%= goal.created_at.year %>/<%= goal.created_at.year + 1 %>

you have to save these values in database, so that u can retrieve them anytime, or you can simply use created_at date of the table(example:- goal.created_at if goals is the table)

Related

How to list down Only the years from specific date on database up to now, using rails?

I want to display a list of years in a drop down, which goes from now to 'established_on' date in database table. And those lists of years should be list of links of years which leads to another page.
Lets say your model is called Post, then you can get the distinct years from the database by doing a query,
Post.distinct.select("date_trunc('year', created_at) AS creation_year")
This will give you all the distinct years that are present in the created_at column. Then if you want to filter the Posts by year, you can use,
Post.where("date_trunc('year', created_at) = '2021-01-01T00:00:00.000Z'")
In Controller:
#club_years = #club.established_on.year..Date.today.year
In view:
<% #club_years.each do |n| %>
<%= link_to n, '#', class: 'dropdown-item' %>
<% end %>

How do I add an attribute to an instance variable in rails 4?

Using Rails 4, in a controller I would like to add an attribute to an instance variable.
Sorry for the poor example, I'm trying to keep it simple.
E.g. In a controller, I create a new instance variable by looking up some users named John. Now, in my controller, I would like to sum up all the ages for all Users named John, put that summed age back in to the instance variable so it is available to the view.
The User model has attributes 'id', 'name' and 'age'.
#foo_users = Users.where(name: 'John')
#foo_users.each do |foo|
#foo_users.age_sum = Users.where(name: 'John').sum(:age) <-- this does not work
end
I have no need to save that summed age back to a database, since I will only use it in one view. I would like to be able to display all the users:
<% #foo_users.each do |user| %>
User name: <%= user.name =>
Sum of ages: <%= user.age_sum %>
<% end %>
Update: I might have over simplified my example. Here is a closer to reality example.
A company owns hotels. Hotels have Rooms. Management software delivers to the company daily Hotel_Statistics via an API. For lack of a better word, these Hotel_Statistics contain the hotel_id, daily check-ins, daily check-outs. In the company's back-office Rails app that I am working on, on the page displayed there is a table of hotels with their given most recent statistics. One line would look like:
Hotel Id: 123
Daily check-ins: 50
Daily check-outs: 48
Hotel Id: 124
Daily check-ins: 35
Daily check-outs: 37
The company wants to also display the running sum of the last 30 days of check-ins (outs, net check-ins).
To accomplish this, in my controller, I find the Hotel_Statics for the most recent date (normally yesterday).
latest_stat = HotelStatistic.order('date DESC, hotel_id DESC').first
#latest_date = latest_stat.date
#recent_stats = HotelStatistic.where(date: #latest_date).order('hotel.id ASC').all
I display the details of #recent_stats in my view.
Now, I would like to display in my view the sum of the last 30 days of #recent_stats.check_ins for each Hotel. My idea was to sum up the the last 30 days of check_ins statistics for a given Hotel like:
#recent_stats.each do |stat|
#last_30_days_check_ins = HotelStatistic.where(hotel_id: stat.hotel_id).where("date >= ?", Date.today - 30).sum(:check_ins)
end
The math works, but I need a way to access the 30 day sum variable for each hotel. I was a hoping to make this easy in the view by adding the hotel 30 day sum to the #recent_stats instance variable so in my view I could do:
<% #recent_stats.each do |statistic| %>
Hotel Id: <%= statistic.hotel_id %>
Daily check-ins: <%= statistic.check_ins %>
Last 30 days check-ins: <%= statistic.last_30_days_check_ins %>
<% end %>
Does this more realistic example change anything in your suggested answers? Thanks
The type of #foo_users is ActiveRecord::Relation. Trying to add age_sum as a new attribute to an ActiveRecord::Relation object doesn't make sense because semantically age_sum is not an attribute of ActiveRecord::Relation objects. It's better to store the sum of ages in a new instance variable, for example #user_age_sum.
UPDATE
Try the following
class HotelStatistic < ActiveRecord::Base
belongs_to :hotel
end
class Hotel < ActiveRecord::Base
has_many :hotel_statistics
def last_30_days_check_ins
self.hotel_statistics.where("date >= ?", 30.days.ago).sum(:check_ins)
end
end
Keep the existing code for building #recent_stats in the controller
In the view
<% #recent_stats.each do |statistic| %>
Hotel Id: <%= statistic.hotel_id %>
Daily check-ins: <%= statistic.check_ins %>
Last 30 days check-ins: <%= statistic.hotel.last_30_days_check_ins %>
<% end %>
Using select should solve your problem:
#users = User.select("*, SUM(age) as age_sum").where(name: 'John')
Now each User in the #users array will have a age_sum property. This is not 100% ideal as the value of the property will be the same on each instance, but it will work with how you've setup your view.
Edit
It's possible to dynamically define a method on an instance manually:
#foo_users.each do |foo|
def foo.age_sum; Users.where(name: 'John').sum(:age); end;
end
However while this is possible, it would have to be a very good use case to justify the negative impact this may have (such as on how readable, efficient and maintainable the code is). There are probably much better OO ways to solve the same problem

Creating a date range picker using two select boxes in Rails

I'd like to setup a model that would allow a date range depicting a timeframe of activity-inactivity. So for example you have an employee model and would be able to set his/her duration of employment from a start date to an end date. Essentially there would be two select boxes that would allow you to do this. If the employee is still employed there would be an option in the second box labeled "current".
I've looked around for an existing answer to this problem and it seems most direct you towards using either date_select or select_year to create a range within one select box. I'm looking to do something of the sort using two select boxes (start / end || current) and saving the two values to the database. Now for the second select box I wanted to have it default to the current year and be called "Current", indicating there is no end date yet.
Looking through the Rails API there's an option for a prompt but I'm not exactly sure how to have that prompt represent a physical value and reside at the top of the list. For something as simple as this I was leaning towards not using an extensive jQuery datepicker plugin to reduce the unnecessary overhead. I'm open to using SimpleForm but haven't found a way to do this through that gem.
What I have now:
<% form_for #product do |f| %>
<%= f.label :employed %>
<%= select_year(Date.today, start_year: 2000, end_year: 2012) %>
<%= select_year(Date.today, :start_year => Date.today.year, :end_year => 8.years.from_now.year) %>
<% end %>
I'm wondering if creating two attributes to the employee model specifying these date (stardate + enddate) would work or could you possibly do this in one fell swoop (I'm assuming the latter would be cleaner)?
I would consider creating a separate table to store these values, call it EmploymentPeriod. An Employee then has_many EmploymentPeriods, which could be useful to keep track of... (maybe an employee is a student, and works one summer, and then returns the following, for example).
EmploymentPeriod could keep track of things like start_date, end_date, and even something like salary, for that particular period (maybe the student gets a raise the following summer...).
To recap:
Employee has_many :employment_periods
EmploymentPeriod belongs_to :employee # e.g. it has an employee_id foreign key
This is how I would tackle it! Good luck.

How do I properly gather information from two tables and use them in one controller in rails?

I have two tables named users and billing. In users I have the usual information, while in billing (contains user_id field for reference) I have things like balances by month for each user. My problem comes from when I want to list the monthly balances. On the monthly balances page I want to display the user(s)'s name, balanace for the month and other misc information, however the billing table only holds the user's id.
At first i tried
#mondetail = Billings.find_by_date(201204) #April's billing period
#customer = Users.find_by_id(mondetail.user_id)
which works fine for one user but how should I go about this when I want to display the information from both tables with multiple users? Or would it just be best for me to add a user_name field to the billing table?
You don't need find user's info in controller. You can get it from Billing model. (Strange that models are plural)
# controller
#mondetail = Billings.includes(:user).find_by_date(201204)
# view
<% #mondetail.each |mondetail| %>
<%= mondetail.user.name %><br />
<%= number_to_currency mondetail.balance %>
<% end %>
It's will work and without includes but you should avoid N + 1 queries problem

Rails Date Select Parameters

I'm using a date select in a rails 3 form.
<%=f.date_select :date %>
I would like to restrict the dates so that you can only pick dates that fall on a Sunday. Is there any way of going about doing this?
I'm also trying to stop dates which have already passed from appearing.
Thanks for any help in advance!
Rails date_select field generates three dropdown to select the parts of the date. There is no chanche, that you modify for example the month, and the day will still be sunday.
You must write some js magic to enforce such a role, or find an already existing datepicker and limit it. Or alternatively, you let the user to select a week, and calculate the exact date of sunday from that.
Ok having studied this out a bit further I don't think this is possible due to the format of the date_select field. The closest I can get is
<%=f.date_select :date, start_year: Time.now.year %>
so that at least you can't select dates from previous years. I've implemented the restriction on days and months that have past by setting up the view to automatically delete records that aren't relevant:
<% if(service.date < Date.today) %>
<% service.destroy %>
<% end %>
Not perfect but does the job in my case.

Resources