简体   繁体   中英

Rails - How to pass data from view or url to helper

In Rails I'm using code from Railscasts #213 revised to build a calendar. I'm using it to display Event hours for each day.

The helper code sets the background-color for today, so you can easily see which day is today.

I have it working so that you can click on a day and a table will show detail records of Events for that day.

This is the code that is executed when the user clicks on a day in the calendar:

<div><%= link_to 'View' , events_index7_path(:date_selected => date), :class => 'btn  btn-mini'%></div>

That puts the selected day into the url, like this:

 .../events/index7?date_selected=2013-11-22

And the view tests for the day_selected like this:

<% current_user.events.where(:event_date => @date_selected).each do |event| %>

I would like to set the css background-color for the date_selected

I'm trying to add the dayselect class to the helper:

def day_classes(day)
  classes = []
  classes << "today" if day == Date.today
  classes << "dayselect" if day == @date_selected
  classes << "notmonth" if day.month != date.month
  classes.empty? ? nil : classes.join(" ")
end

But, it doesn't recognize @date_selected

I also tried this:

classes << "dayselect" if day == params[:date_selected]

UPDATE1:

This is a pic of the calendar so you better understand what I'm doing:

在此处输入图片说明

UPDATE2

View code for the calendar:

  <%= calendar @date do |date| %>
  <%= date.day %>
  <% hours = current_user.events.where(:event_date => date).sum(:hours) %>
  <% if hours != 0 %>
    <div class="sumhours"><%= hours %></div>
  <% else %>
    <div> - </div>
  <% end %>
  <div><%= link_to 'View' , events_index7_path(:date_selected => date), :class => 'btn  btn-mini'%></div>

UPDATE3 If I stop execution at the helper code to set the class, I find this:

Request parameters  
{"date_selected"=>"2013-11-21", "controller"=>"events", "action"=>"index7"}

How do I access the date_selected parameter?

UPDATE4

This will highlight a specific date converted from a string:

classes << "dayselect" if day == DateTime.strptime("2013-11-18", "%Y-%m-%d")

But, if I used this:

  classes << "dayselect" if day == DateTime.strptime(params[:date_selected], "%Y-%m-%d")

I get:

undefined local variable or method `params' for #<CalendarHelper

I couldn't figure out how to do it with Rails, so I used jQuery.

Used pure.js to get the url.

Here's the jQuery (Coffeescript):

url = $.url().param("date_selected")

$("#monthcalendar td").each ->
  $(this).addClass "dayselect" if $(this).attr('class') == url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM