1

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 class="well well-sm"> <div class="p-3 mb-2 bg-warning text-dark"> <p class="text-warning h1 text-center"><%= title %></p> <p class="h4"><%= text_consent %></p> <div class="cotainer" 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?

3
  • can you show the content of your partial? (_consent.html.erb)?CommentedAug 12, 2022 at 11:29
  • Yes. There I modified it.
    – Lucho
    CommentedAug 12, 2022 at 11:40
  • See my updated answer which should work.CommentedAug 13, 2022 at 16:17

1 Answer 1

3

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'} %>")

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.