【发布时间】:2015-07-31 20:19:40
【问题描述】:
目标是在索引页面上创建、编辑和销毁模型类别。我可以保存模型,但无法刷新列表。我读过很多类似的例子,令人困惑。
这就是我所拥有的:
在视图/类别/index.html.erb
<!-- Full expand -->
<div class="row mt-20">
<div class="well-basic">
<div class="col-xs-8">
<table class="table">
<thead>
<tr>
<th>Content</th>
<th>Actions</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @categories.each do |category| %>
<tr>
<td><%= category.content %></td>
<td> Edit |
<%= link_to '', category, method: :delete, data: { confirm: 'Are you sure?' }, class: 'glyphicon glyphicon-remove' %> </td>
</tr>
<% end %>
</tbody>
</table>
</div>
<div class="col-xs-4">
<%= render '/categories/form', :locals => {:category => @category} %>
</div>
</div>
</div>
<!--/ Full expand -->
这是 app/categories/_form.html.erb 中的表单
<%= simple_form_for(@category, remote: true ) do |form| %>
<%= form.error_notification %>
<div class="form-inputs">
<%= form.input :content %>
</div>
<div class="form-actions">
<%= form.button :submit, class: 'btn btn-success custom-reload' %>
</div>
<% end %>
好像麻烦来了:在 app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
def index
@user = current_user
@categories = @user.categories
@category = Category.new
end
def create
@user = current_user
@category = @user.categories.build(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @categories, notice: 'Category has been sucesifully created' }
format.js { }
format.json { render json: @category, status: :created, location: @category }
else
format.js { render @categories, notice: 'Category could not been saved.' }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
def destroy
@category = Category.find(params[:id])
@category.destroy
redirect_to :back
end
private
def category_params
params.require(:category).permit(:content)
end
end
这是 app/views/categories/create.html.erb。第一行有效,第二行无效。
$("<%= escape_javascript(render @category") %>).appendTo("#categories")
$('.custom-reload').on('click', function() {
window.location.reaload();
});
请帮助,有人知道如何刷新页面。甚至,更好的是,有人有关于列表中这种常见表单用法的完整示例吗? (我什至还没有尝试编辑,但已经删除了作品)。谢谢。
【问题讨论】:
-
看起来像一个拼写错误
window.location.reload();,但通常使用 Ajax 的模式是您通过修改 DOM 而不刷新来避免重新加载(就像您在create.html.erb的第一行中一样)。所以第一行应该是你所需要的,除非你希望执行 JS,它应该被称为create.js.erb(首先执行嵌入式 Ruby,然后在浏览器中执行生成的 JS)。 -
感谢@steveklein 的评论。我解决了这个问题和其他错字,但仍然没有奏效。我现在有一个完整的实现工作,并将用它来回答这个问题。虽然还很简单,但我相信可以改进。也许您或其他人可以举例说明编辑或更多功能。再次感谢。
标签: ruby-on-rails ruby ruby-on-rails-4