I have a route called "/admin", which is used to add and list products, from:
resources :products, controller: "admin"
In the controller admin I have a create function:
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
When I tried to make it render to format.js, it said:
ActionController::UnknownFormat
on `respond_to do |format|`
I thought created admin/create.js.haml:
console.log("got it")
but it doesn't work.
Why did I want the response to be "format.js"? Because I want to add an error message to the form and don't want to refresh the page, so I respond to the JavaScript to append on some div with the error message.
This is 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'
How do I use format.js in Haml for this?
format.htmlis handler for html request andformat.jsis handler for ajax request. You must be submitting form normally instead of AJAX and so get this error. Share your haml code as well.id: #this-errorso I that is why I need to use javascript to not refresh the page when the forms is empty, so when i submit"Add"the form empty and must get error messageremote: trueto the form if you want to make an ajax request