Venomoustoad
Venomoustoad

Reputation: 1213

how do I embed a Ruby object in JavaScript?

I am trying to embed Ruby in the JS.erb file, where I want to be able to access the @user object and all its relations.

  1. I do not want to convert to JSON object. I want the ERB to precompile on server-side.
  2. I do not want to iterate in the view but in the JS file. How should i be structuring my controller/ view / js.erb file to make this work?

Controller - user_controller

 class UsersController < ApplicationController

      def index
      end

 end

Model - user.rb

class User < ActiveRecord::Base
  attr_accessible :email, :first_name, :last_name
  has_many :qualification_rs
end

View - Users.html.erb is blank ( i want to purely get my code from JS)

<html>
<body>
</body>
</html>

Javascript asset - users.js.erb

$(document).ready(function(){
<% @users.each do |user| %> 
$('body').append(<% = user.first_name%>);
<%end%>
});

The following error appears

"undefined method `each' for nil:NilClass" i.e. it does not recognize @users in the js file. (it does in the user.html.erb file from which i am including the javascript tag. What else do i do to get the instance object to be recognized within the js file?

Upvotes: 3

Views: 1575

Answers (3)

Venomoustoad
Venomoustoad

Reputation: 1213

I am not sure whether the question was too clear- here was the final resolution.

I finally had to include within tags the piece of JS within Users.html.erb instead of including the JS as a separate file within assets/ public.

The @ users variable is accessible directly only in the HTML file within the views folder and not from the assets directories directly.

Upvotes: 0

Salil
Salil

Reputation: 47462

check for @users is present or not like following

  <% @users.each do |user| %> 
    $('body').append("<p><%= user.first_name %></p>");
  <% end if @users%>

Upvotes: 0

Antoine
Antoine

Reputation: 2807

Use <%= and %> (and the ruby/rails doc)

    $(document).ready(function(){
      <% @users.each do |user| %> 
      $('body').append("<p><%= user.first_name %></p>");
      <%end%>
    });

Upvotes: 1

Related Questions