3

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 %>, <%=@work.user.fname %></td><td><%= link_to(@work.project.name, @work.project, 'data-no-turbolink' => true) %></td><td><%=@work.datetimeperformed%></td><td><%=@work.hours %></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

Community
  • 1
  • 1
Mike G
  • 751
  • 3
  • 12
  • 21
  • Where is your `create.js.erb` located? – JTG Jan 02 '15 at 21:06
  • @JTG - create.js.erb is located in views/works directory – Mike G Jan 02 '15 at 21:30
  • 1
    Using Chrome, open the developer tools and click on the Network panel. Perform the action in your app that triggers the new row to be inserted. In the Network panel, click on the request name corresponding to that request, and look at the "Response". See if the html generated by link_to is causing invalid js syntax. Post the generated response in your question too – jemminger Jan 02 '15 at 21:51

1 Answers1

2

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.

Camway
  • 1,010
  • 14
  • 23