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.
- I do not want to convert to JSON object. I want the ERB to precompile on server-side.
- 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?