【发布时间】:2016-08-22 20:27:46
【问题描述】:
我在这里尝试使用 select_tag 来过滤汉字单词列表。
我的想法是当用户从下拉列表中选择选项 -> 自动提交表单 -> 使用 AJAX 获取search_by_lesson 操作并将数据填充到#kanji_list。但我遇到了两个问题:
- 虽然我的
form_tag中有remote: true,但当我从下拉列表中选择时,浏览器仍会导航到新页面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>
我使用部分渲染列表_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') %>")
【问题讨论】:
-
尝试在控制器中添加 respond_to 块
标签: jquery ruby-on-rails ajax