我有一条名为"/admin"
的路线,用于从以下位置添加和列出产品:
resources :products, controller: "admin"
在控制器管理员中,我具有create
功能:
def create
@product = Product.new product_values
respond_to do |format|
if @product.save
format.html { redirect_to :root }
else
format.js { render 'admin/error' }
end
end
end
[当我尝试使其呈现为format.js时,它说:
ActionController::UnknownFormat
on `respond_to do |format|`
我以为创建了admin/create.js.haml
:
console.log("got it")
但不起作用。
为什么我希望响应为“ format.js”?因为我想向表单添加错误消息,并且不想刷新页面,所以我在JavaScript上将div的错误消息响应到[div]上的append
。
这是admin/add_product.html.haml
:
.p-5
.container.column.justify-content-center
%div.d-flex.justify-content-center.p-4#this-error
%div
%h3
Add Product
%div
= form_for (@product || Product.new) do |f|
.form-group.row
= f.label :name, class: 'col-md-2 col-form-label'
%br/
.col-sm-8
= f.text_field :name, class: 'form-control'
.form-group.row
= f.label :stock, class: 'col-md-2 col-form-label'
%br/
.col-sm-2
= f.number_field :stock, class: 'form-control'
.my-4
= f.label :price, class: 'ml-5 col-md-1 col-form-label'
%br/
.col-sm-2
= f.number_field :price, class: 'form-control'
.form-group.row
= f.label :desc, class: 'col-md-2 col-form-label'
%br/
.col-sm-8
= f.text_area :desc, class: 'form-control'
.d-flex.justify-content-center
= f.submit "Add", class: 'btn btn-primary col-sm-8 p-2'
我该如何在Haml中使用format.js?
您正在通过表单提交本地请求,而不是远程提交(AJAX请求),因此您的
format.js
将永远不会被调用。
您可以做的是:
def create
@product = Product.new product_values
respond_to do |format|
format.html {
if @product.save
redirect_to :root
else
render 'admin/error'
end
}
format.js { }
end
end