I am working with ruby on rails (rails 4.2). Given a validation done in javascript I need to run a ruby tag or not. I found something similar here but it didn't work for me.
html:
<div id="consent">
//this is the code that sholuld put with
//render partial: 'consent', :locals => {:text_consent => foo, :title => 'Title'} %>
</div>
Javascript:
$(document).on 'click', '#next_page', (event) ->
event.preventDefault()
$("#consent").append('<%= render partial: \'consent\', :locals => {:text_consent => foo, :title => \'Title\'} %>')
return
this is the content of the partial:
<div >
<div >
<p ><%= title %></p>
<p ><%= text_consent %></p>
<div style="text-align:center; vertical-align:middle;">
<%= check_box_tag 'accept_consent', '0', false, :style => "width: 50px; height: 50px;" %>
</div>
</div>
</div>
Como resultado obtengo esto en el html (as a string):
<div id="consent">
"<%= render partial: \'consent\', :locals => {:text_consent => foo, :title => \'Title\'} %>"
</div>
I know that ruby and javascript are two executions in different environments, but is there any way to do something like this or similar?
CodePudding user response:
I think it's important to keep in mind the framework locations. JavaScript is in the browser, Ruby is on the server.
So to get JavaScript to add/execute Ruby code, you're going to have to make a request to the server.
There are lots of options, primary: AJAX, UJS, and Turboframes (Rails 7).
In your case, the document.on('click' ...
event needs to make a call to a controller action that will return executable JavaScript, which is possible with a *.js.erb
file.
There are lots of really good Rails tutorials for this.
This one covers AJAX and Rails UJS really well: https://www.rubyguides.com/2019/03/rails-ajax/
In your case, you can have the Ruby load the partial as HTML on page load and then use JavaScript to display it on click.
This should work as long as you escape your JavaScript with j
$("#consent").append("<%= j render partial: 'consent', :locals => {:text_consent => foo, :title => 'Title'} %>")