简体   繁体   中英

How can I incorporate .addClass jQuery code into a Ruby on Rails callback method?

I'm creating a to do list web app that creates task items with varying priority levels (Low,Medium,High). What I'd like to do is to have the corresponding CSS class added to the element depending on the Priority.

  1. Low = Green
  2. Medium = Orange
  3. High = Red

This is what I have for my index.html.erb. (I don't know if this is relevant but I made my task logic into a partial):

<% @tasks.each do |task| %>
<tr>
  <td><%= task.name %></td>
  <td><%= task.description %></td>
  <td><%= task.start %></td>
  <td><%= task.finish %></td>
  <td><%= task.importance %></td>
  <td><%= link_to 'Edit', edit_task_path(task) %></td>
  <td><%= link_to 'Remove', task_path(task), method: :delete, 
      data: { confirm: 'Are you sure you would like to Delete? Did you complete the  
      task?' } %></td>
</tr> 
<% end %>

I have a priority.js.erb file that contains the following code:

$(document).ready(function(){
  if (<% @task.importance == "Low" %>) {
    $("td").addClass("green");
  } 
  else if(<% @task.importance == "Medium" %>) {
    $("td").addClass("orange");
  } 
  else {
    $("td").addClass("red");
  }
});

The error message that I receive is:

ndefined method `importance' for nil:NilClass

Am I on the right track here? I originally thought of having an after_create: , after_update: callback in my controller but then I realized that I don't think I can use jQuery code in a .rb file.

I was thinking something like this:

class Task < ActiveRecord::Base
  after_create do |task|
    some javascript code to change the color
  end
end

Any suggestions?

Your JavaScripts are requested during a completely separate request/response cycle from the main HTML of your page. There will not be an @task variable, as no controller is involved in serving up your assets.

You need to move your code into the body of your page, or at least serve up the value of @task.importance during the main request when your controller's action is actually invoked and @task is defined.

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