索引视图显示所有类别和添加新表单的表单。在提交表单时,我希望新类别出现在列表中。表单提交,类别被保存,我可以在日志中看到create.js.erb被渲染。但新类别未添加到视图中。我是否需要将控制器中的create操作重定向到索引视图?或者如何在列表中显示新类别
index.haml
%div{class: "col-md-4 col-md-offset-2 category-list"}
- @categories.each do |cat|
= render 'category', category: cat
%div{class: "col-md-4"}
.btn.btn-success.btn-sm.add-category
Add a category
.add-category-form
= form_for [:admin, @category], remote: true, html: {class: "category disabled"} do |f|
- if @category.errors.any?
#error_explanation
%h2
= pluralize(@category.errors.count, "error")
prohibited this category from being saved:
%ul
- @category.errors.full_messages.each do |msg|
%li
= msg
.category-add
.form-group
= f.label :name
= f.text_field :name, class: "form-control"
.form-group
.controls
= f.submit '+ Add', class: 'btn btn-success'
create.js.erb
$('.add-category-form').hide();
$('.category-list').append("<h4><%= @category.name %></h4>");
// set form values to blank
$('.add-category-form.input').each(function() {
$(this).val('');
})
categories_controller.rb
def create
@category = Category.new(categories_params)
if @category.save
respond_to do |format|
format.html { }
format.js { }
end
else
flash[:error] = "Correct the errors as indicated"
render :new
end
end