I want to render my form partial in javascript erb file. When I place it in there it gives me a no method error. Any ideas?
script.js.erb
$(document).ready(function() {
$(".enquiry-button").click(function(e) {
e.preventDefault();
e.stopPropagation();
if ($(this).parents('.cell').find('form').length == 0) {
$(this).closest('.cell').append(
"<div class='enquiry-form'>" +
"<%= escape_javascript( render '/static/form' ) %>" +
"</div>");
$(this).closest('.cell').find(".enquiry-form:last").slideDown("slow");
} else {
$(this).closest('.cell').find(".enquiry-form:last").slideToggle("fast");
}
});
});
_form.html.erb
<%= simple_form_for @user do |f| %>
<%= f.error_messages %>
<%= f.input :email %>
<%= f.button :submit %>
<% end %>
error
NoMethodError in Static#home
Showing /Users/colton/kitchen_ninja/kitchen_ninja/app/views/layouts/application.html.erb where line #6 raised:
undefined method `render' for #<#<Class:0x007f90cc875c80>:0x007f90cd2017e0>
(in /Users/colton/kitchen_ninja/kitchen_ninja/app/assets/javascripts/script.js.erb)
Extracted source (around line #6):
You are mixing two separate things together. Your render
needs to run on the server. JavaScript's job is just to make an AJAX request and get a resource.
So, supposed you were to to this:
$.ajax(url: "/test").done(function(html) {
$("#results").append(html);
});
AJAX's only role is to grab a remote resource and parse the results.
In Ruby, you can use render
to emit the HTML:
<%= escape_javascript( render '/static/form' ) %>
Just make sure you point the AJAX request to the right resource so Ruby can do the rest of the magic.
Since you are pre-processing the script with .erb
, you could use Ruby's string interpolation to return the partial as a string literal in the JavaScript file.
html = "<div class='enquiry-form'>" +
"#{j render partial: 'static/form'}}" +
"</div>"
$(this).closest('.cell').append( html );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.