在循环中更新js.erb文件的变量

时间:2016-01-20 22:43:15

标签: ruby-on-rails ajax

我有一个form_for和一个按钮的部分。我使用activate_item.js.erb文件渲染此部分,并希望能够在索引视图中访问实例变量。

activate_item.js.erb:

<%= form_for :c, url: activate_item_item_url(c.id), :html => {:id => "cc_form_#{c.id}", :class => "cc_form_class"}, :method => "put", :remote => true do |k| %>
<%= button_to "#{c.recyclable}", {:url => "activate_item_item_url", :controller => :items, :action => :activate_item, :id => "item_recyclable_#{c.id}"}, :class => 'btn btn-success btn-sm' %>
<% end %>

index.html.erb:

<% @items.each do |c| %>
        <tr>   
          <td><%= c.description %></td>
          <td><%= c.color %></td>
             <% if c.active_recyclable_second %>
                <td><%= button_to "ON", {:controller => :items, :action => :activate_recyclable_second, :id => c.id}, :method => :put, :class => 'btn btn-danger btn-sm' %></td>
             <% else %>
                <td><%= button_to "OFF", {:controller => :items, :action => :activate_recyclable_second, :id => c.id}, :method => :put, :class => 'btn btn-danger btn-sm' %></td>
             <% end %>
             <div id="cc_form_ext_#{c.id}">
               <td><%= render "items/recyclable_update", c: c %></td>
            </div>
        </tr>
      <% end %>

activate_item.js.erb:

$('#cc_form_ext_<%= @item.id %>').append('<%= escape_javascript(render 'recyclable_update') %>');

我已经读过我需要使用新的ajax调用来更新c变量。 Rails 3: Instance variable inaccessible in .js.erb file但我不确定该怎么做。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

我找到了。我在语法上错过了在js.erb中添加c:@item。 $(&#39;#cc_form_ext_&lt;%= @ item.id%&gt;&#39;)。html(&#39;&lt;%= escape_javascript(渲染&#39; recyclable_update&#39;,c:@item )%&gt;&#39;);