简体   繁体   中英

Can I have a javascript partial in Ruby on Rails? Partial is trying to render in HTML

I have a function that simple selects all of the checkboxes on the current page, creates a form, and submits it automatically.

Instead of repeating the same exact javascript code on every single view, I want to try to just have a shared partial.

Here's all I have thus far:

#views/shared/_delete_multiple_items.js.erb
alert("<%= random_variable %>");

.

#views/users/index.html.erb
...
<script>
  function deleteMulitpleUsers() {
    <%= render 'shared/delete_multiple_items', :locals => {:random_variable => "Hello World" %>
  }
</script>

It looks like Rails is trying to render the partial in HTML though, if I understand this error correctly:

Missing partial shared/_delete_multiple_items with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:

I've tried to include :formats => :js with render, like this:

<%= render 'shared/delete_multiple_items', :locals => {:random_variable => "Hello World", :formats => :js %>

but I still get the same exact error. Any help would be greatly appreciated.

Have you tried adding aj on your js.erb file?

#views/shared/_delete_multiple_items.js.erb
alert("<%= j random_variable %>");

You get that error because server responding format is html, not javascript. Setting response format is done in controller so putting format: :js in templates won't work. Try these steps and see if they work for you.

  1. Rename _delete_multiple_items.js.erb to _delete_multiple_items.html.erb

  2. Put alert("<%= random_variable %>"); inside <script> tag

  3. In index.html.erb , remove all js related code and just do <%= render 'shared/delete_multiple_items', :locals => {:random_variable => "Hello World" %>

Change this:

<%= render 'shared/delete_multiple_items', :locals => {:random_variable => "Hello World" %>

to this:

<%= render partial: 'shared/delete_multiple_items', formats: :js, :locals => {:random_variable => "Hello World"} %>

partial: at the beginning to tell rails to look for a partial and formats: :js to tell rails to look for a js file (note that formats is NOT a child of locals )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM