Rails - Как получить доступ к значению индекса в частичном - PullRequest
0 голосов
/ 03 октября 2018

Я пытаюсь использовать встроенный рельс ajax для добавления элемента в список после того, как пользователь заполняет форму. Однако я не могу настроить таргетинг на тег div, чтобы добавить новую запись: ActionView::Template::Error (undefined local variable or method '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) %>');

Как получить доступ к значению индекса из Клиентов / Индекс?

Ответы [ 2 ]

0 голосов
/ 03 октября 2018

В вашем 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) %>');

Надеюсь, эта помощь.

0 голосов
/ 03 октября 2018

Я думаю, вам придется передать переменную 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) %>');
...