Mike G
Mike G

Reputation: 751

link_to method causes jquery to not load in js.erb

I am trying to to use a jquery .insertafter method to dynamically insert a row in a table. I have my code in 'create.js.erb' as below:

$("<tr><td><%= @work.id %></td><td><%= @work.user.lname %>, <%[email protected] %></td><td><%= link_to(@work.project.name, @work.project, 'data-no-turbolink' => true) %></td><td><%[email protected]%></td><td><%[email protected] %></td></tr>").insertAfter("tr#headerrow");

The code works perfectly fine as long as I don't use the 'link_to' method. The moment I use 'link_to', it stops working.

I tired adding an alert before the 'insertafter' method. Adding link_to doesn't even fire the alert.

The page seems to be rendering fine without javascript errors. rails console log looks fine:

User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 281110143]]
Project Load (0.1ms)  SELECT  "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1  [["id", 730774123]]
Rendered works/create.js.erb (3.0ms)

This is my controller code where I am calling create.js.erb. The format.js {} calls create.js.erb.

  def create
   @work = Work.create(work_params)

   respond_to do |format|
     if @work.save
       format.html {redirect_to @work, notice: 'Work Created'}
       format.js { render content_type: 'text/javascript'}
     else
       format.html {render 'new'}
       format.js {}
     end
   end

end

I tired this solutions from Stack overflow regarding turbolinks and that didn't help either.

Rails, javascript not loading after clicking through link_to helper

Rails 4: disable Turbolinks in a specific page

Using turbolinks in a Rails link_to

Appreciate your help in this.

Thanks! Mike G

Upvotes: 3

Views: 672

Answers (1)

Camway
Camway

Reputation: 1062

Can I see the version with the link_to in place?

I can't tell from what you've provided but are you sanitizing your html before putting it into the jquery string?

What I think you're doing:

$("<%= link_to 'whatever', 'whatever' %>")
#=> $("<a href="whatever">whatever</a>")

What you should be doing:

$("<%=j link_to 'whatever' %>")
#=> $("<a href=\"whatever\">whatever</a>")

The 'j' in the beginning is a method that makes sure it won't escape from a javascript string.

Without more information this is my best guess.

Upvotes: 2

Related Questions