2

In my view I want to create a javascript object that matches my ruby object current_user

Seems like a good solution instead of making an extra request to /users/me.

2 Answers 2

6

This took me longer than it should have:

<script>
  window.current_user = <%= raw(current_user.to_json) %>;
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for doing a self-answered question for this! It also took me longer than it should have.
0

send json from controller to view

def show_user_categories
     @categories= current_users.categories.map do |c|
      { :id => c.id,:name => c.title}
    end   
    respond_to do |format|
      format.html
      format.json { render :json => @categories}
    end
 end 

fetch the json in view

   <%= javascript_tag do%>
     window.categories= <%=raw @categories.to_json %>;

    <%end%> 

and then use it in js script

var markers=[];
 $.each(categories, function(index) {
     //creating js array which can be used in js script
     //using the id/title passed from controller code                 
     markers.push([categories[index]['id'],categories[index]['title']]);

 });

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.