Search code examples
javascriptjqueryruby-on-railsrubyruby-on-rails-2

Trouble passing ruby to javascript (jquery)


I'm having trouble passing a ruby array to jquery in Rails 2.3. What are best practices for passing ruby data to jquery? Below I am trying to write a bit of jquery that responds to rails controllers and controller actions.

  <% action_array = [params[:controller], params[:action]] %>

    <script type="text/javascript">

    $(document).ready( function() { 

      var path =  <%= action_array.to_json %>;

        if ( path[0] == "home" ) {
    $('.home').addClass('gradientBGRed');
}

});

    </script>

</head>

<body>

<ul id="headerNav" class="gradientBG">
<li class="home "><a href="/">Home </a></li>
<% if logged_in? %>
  <li class="register "><a href="/account">Account </a></li>
 <li class="login last"><a href="<%= logout_path %>">log out </a></li>
  <% else %>
  <li class="register "><a href="/customers/new">register </a></li>
    <li class="login last "><a href="<%= login_path %>">log in </a></li>
<% end %>
</ul>

Solution

  • there is something wrong with your selector

    $('.home').addClass('gradientBGRed');

    the dot is important because it is a class you are search for