3

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?

3 Answers 3

1

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

    $(document).ready(function(){
      <% @users.each do |user| %> 
      $('body').append("<p><%= user.first_name %></p>");
      <%end%>
    });
Sign up to request clarification or add additional context in comments.

2 Comments

"undefined method `each' for nil:NilClass" i.e. not that i am not running the erb file on html but on the js file in the assets folder. 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?
You need to instanciate it in your controller like @user = User.find(1) for example
0

check for @users is present or not like following

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.