Rails-如何局部访问索引值

时间:2018-10-03 01:58:53

标签: ruby-on-rails ajax ruby-on-rails-5 partial-views renderpartial

在用户填写表单后,我尝试使用内置的rails ajax将项目追加到列表中-但是,我无法将div标签定位为将新条目追加到:ActionView::Template::Error (undefined local variable or method 'index' < / p>

客户/索引:

<% @clients.each_with_index do |client, index| %> 
  <div id="communication_pane<%= index %>">
    <%= render client.communications.order(created_at: :desc) %>
  </div>

  <%= form_for([@clientlist, client, client.communications.build], remote: true) do |f| %>
  <%= f.text_area :content, class: "form-control", id: "communication_content#{index}" %>
  <%= f.submit("New Communication") %>
<% end %>

Communications / create.js.erb:

$('#communication_pane<%= index %>').prepend('<%= escape_javascript(render @communications) %>');

如何从“客户/索引”中访问索引值?

2 个答案:

答案 0 :(得分:1)

在您的create.js.erb中,index处有一个未定义的变量$('#communication_pane<%= index %>')
因为服务器无法知道您单击客户端的位置,所以您必须明确告知服务器有关此信息。这是一个主意:

<!-- app/views/clients/index.html.erb -->
<% @clients.each_with_index do |client, index| %> 
  <div id="communication_pane<%= index %>">
    <%= render client.communications.order(created_at: :desc) %>
  </div>

  <%= form_for([@clientlist, client, client.communications.build], remote: true) do |f| %>
    <%= f.text_area :content, class: "form-control", id: "communication_content#{index}" %>
    <!-- Letting server know the index of current form by adding a param -->
    <%= hidden_field_tag :client_index, index %>
    <%= f.submit("New Communication") %>
  <% end %>
<% end %>

然后在您的js.erb文件中,使用params[:client_index]代替index

# app/views/communications/create.js.erb
$('#communication_pane<%= params[:client_index] %>')
  .prepend('<%= escape_javascript(render @communications) %>');

希望获得帮助。

答案 1 :(得分:0)

我认为您必须将index变量作为hidden_field传递到控制器操作,然后在create.js.erb上显示它

客户/索引:

<% @clients.each_with_index do |client, index| %> 
  <div id="communication_pane<%= index %>">
    <%= render client.communications.order(created_at: :desc) %>
  </div>

  <%= form_for([@clientlist, client, client.communications.build], remote: true) do |f| %>
  <%= f.hidden_field :index, value: index %>
  <%= f.text_area :content, class: "form-control", id: "communication_content#{index}" %>
  <%= f.submit("New Communication") %>
<% end %>

communications_controller

def create
  @index = params[:communication][:index]
  ...
end

Communications / create.js.erb

$('#communication_pane<%= @index %>').prepend('<%= escape_javascript(render @communications) %>');