我试图在这里使用select_tag来过滤汉字单词列表。
我的想法是用户从下拉列表中选择选项 - >自动提交表单 - >使用AJAX进行search_by_lesson
操作并将数据填充到#kanji_list。但我遇到了2个问题:
remote: true
中有form_tag
,但当我从下拉列表中选择时,浏览器仍会导航到新页面http://localhost:3000/search_kanjis_by_lesson?lesson=1
,但不会停留在索引页面。search_by_lesson
仅由ajax呈现,但我不想在文件夹中单独search_by_lesson.html.erb
。这是我的index.html.erb
<%= form_tag search_kanjis_by_lesson_path(lesson: params[:lesson]), method: :get, remote: true do |f| %>
<%= select_tag :lesson, options_for_select(@lessons), include_blank: true, onchange: "this.form.submit()" %>
<% end %>
<table class="ui celled padded striped table">
<thead>
<tr>
<th>Kanji</th>
<th>Meaning</th>
<th>Lesson</th>
</tr>
</thead>
<tbody class="kanji_list">
<%= render 'index' %>
</tbody>
</table>
我使用partial来呈现列表_index.html.erb
<% @kanjis.each do |kanji| %>
<tr>
<td><%= kanji.word %></td>
<td><%= kanji.meaning %></td>
<td><%= kanji.lesson %></td>
</tr>
<% end %>
我在路线中得到了这个
resources :kanjis
get '/search_kanjis_by_lesson', to: 'kanjis#search_by_lesson', as: :search_kanjis_by_lesson
和我的kanjis_controllers.rb
class KanjisController < ApplicationController
# ... other generic actions: edit, show ...
def index
@kanjis = Kanji.all
@lessons = [*1..32] # @lessons is just an array of int.
end
def search_by_lesson
@kanjis = Kanji.find_by_lesson params[:lesson]
end
end
最后,我有一个search_by_lesson.js.erb
$("#kanji-list").html("<%= escape_javascript(render 'index') %>")
答案 0 :(得分:0)
这应该对你有用
在index.html.erb
中max_align_t
在您的application.html.erb
中<%= form_tag search_kanjis_by_lesson_path, method: :get, remote: true do %>
<%= select_tag :lesson, options_for_select(@lessons), include_blank: true %>
<% end %>
在你的KanjisController中
$(document).ready(function(){
$('#lesson').change(function(){
$('form').submit();
});
});
在您的search_by_lesson.js.erb
中 def search_by_lesson
@kanjis = Kanji.find_by_lesson params[:lesson]
respond_to do |format|
format.js
end
end