Rails: Rendered JS file doesn't execute using UJS

Posted by Hassinus on Stack Overflow See other posts from Stack Overflow or by Hassinus
Published on 2012-10-06T21:33:46Z Indexed on 2012/10/06 21:37 UTC
Read the original article Hit count: 210

Filed under:
|

I would like to display a Rails edit form using JS instead of redirecting with HTML.

To do this, I use UJS for the edit link:

<%= link_to "Edit user info", edit_user_path(1), :remote => true %>

Then, the "edit" action of User controller is like this (simplified version):

controllers/users_controller.rb:

def edit

    # Step 1: Get the edit HTML form
    @html = render_to_string(:template => "users/edit.html")

    # Step 2: Use JS to display the form in the correct place
    render "users/edit.js"

end

As you may guess, I have two views:

  • The html version of "edit" action which contains the form in HTML format. Let's consider a test version:

    views/users/edit.html.erb:

    <h1>This is just a test</h1>
    
  • The js version that will display the form in the correct place, using jQuery for example. Again, for test purpose, let's just popup the html text:

    views/users/edit.js.erb:

    alert("<%= @html %>");
    

The problem is that nothing is executed (no popup)

Using the inspector (from Chrome web browser), I get the response as text format:

alert("<h1>This is just a test</h1>");

Do you have any idea? Why do the rendered JS is not executed?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ujs