2

I would like two .js.erb files, named "create" and "update" to load and be executed to replace a table in one of my views with an updated partial after a form is submitted.

The files both contain the following (they are identical)

$('table#rating').replaceWith("<%= escape_javascript(render :partial => 'home/rating') %>");

However I am unsure where to put the .js.erb files (in the same view as my html.erb page?) and how to load/trigger them when the form submits. Any help would be appreciated.

2 Answers 2

3

Yes, you place .js.erb files in the same location as the .html.erb files you're using them with. In order for Rails to use them, you need to tell Rails that the form should be submitted asynchronously (via AJAX). To do this, just add a :remote => true to your form tag. For instance

<%= form_for @some_model, :remote => true do %>
<!-- form stuff... -->
<% end %>
Sign up to request clarification or add additional context in comments.

3 Comments

I have done these things and still the files do not load. Are the names right? Or maybe does something have to be done in the controller?
Are you including rails.js and something like jQuery-Rails?
Then you should make sure your methods and/or controller responds_to AJAX requests.
2

In order to submit a form with Ajax, you need to specify :remote => true option as pointed out by Alex.

In the controller that handles the form submission should also be able to respond to Ajax request. It should have something like following.

class FormHandlingController < ApplicationController

  def create
    ...
    respond_to do |format|
      format.js
    end
  end

end

You should place your craete.js.erb under app/views/form_handling_controllers/ directory.

1 Comment

Thank you for this! This was driving me crazy all day. I couldn't figure out why my js.erb files weren't working, and I was missing format.js in the respective controllers.

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.