Reputation: 1203
Rails version 6.0.2.1 Ruby version 2.6.5
I am trying to render a partial in a show view of my application using jquery.
This is my javascript file:
import $ from "jquery";
$(() =>
$("a#test-button").on("click", ev => {
ev.preventDefault;
$("div#teacher-form").html("<%= j render(partial: 'teacher_form') %>");
})
);
I then referenced the javascript in the view template like so:
<%= javascript_pack_tag 'test_button' %>
<%= link_to 'Test', stakeholder_student_school_year_path, data: { type: :html }, remote: true, id: 'test-button', class: 'btn btn-info' %>
<div id="teacher-form"></div>
And in my controller as well:
def show
@teachers = @year.teachers
respond_to do |format|
format.html
format.js {
render 'student_school_years/_teacher_form',
layout: false
}
end
end
When I click the test button to add the partial it renders in the view the following snippet of code <%= j render(partial: 'teacher_form') %> instead of the actual partial template. Cannot figure out what's going on.
Upvotes: 0
Views: 1806
Reputation: 101811
You seem to have completely misunderstood how JS.erb templates work.
You don't reference .js.erb
templates with javascript_pack_tag
. Thats for referencing assets in the assets pipeline. And you cannot render partials in the assets pipeline since they are compiled at deploy time.
The reason you are just getting a literal string "<%= j render(partial: 'teacher_form') %>"
is that assets are not sent through ERB in webpack. Sprockets would have done it and raised an error.
Instead you would write your js.erb
template so that it alters the page:
def show
@teachers = @year.teachers
respond_to do |format|
format.html
format.js # renders show.js.erb
end
end
// You can't use imports since this is not run in the assets pipeline
// you have to make jQuery a global
$("#teacher-form").html("<%= j render(partial: 'teacher_form' %>");
When you click the link the Rails ujs driver actually just loads that script and evaluates it on the page. The premise is that this lets you do ajax requests and SPA like stuff without a SPA framework or actually writing request handlers. If its a good idea or not is debatable.
What I don't understand is why you don't just put the form in the view in the first place and just toggle its visibility instead of making the server complicit it what is just a client side transformation.
Upvotes: 1