Rails - 如何访问部分索引值

Rails - How to access index value in partial

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

Clients/Index:

<% @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) %>');

如何从 Clients/Index 访问索引值?

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

clients/index:

<% @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) %>');

在您的 create.js.erb 中,$('#communication_pane<%= index %>')
处有一个未定义的变量 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) %>');

希望对您有所帮助。