Is it possible to do model error reporting without a new method? It is my understanding that when you want to report errors you would create the following controller code:
def new
@product = Product.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @product }
end
end
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render json: @product, status: :created, location: @product }
else
format.html { render action: "new" }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
And then you would create a form with the following code within it:
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
However, can you replicate this technique only using a ‘create’ method in the controller? For example, using a form_tag to pass data to the ‘create’ method. Maybe something like this:
‘post’, :class => ‘form-horizontal’, :style => ‘text-align:center’) do %>
<% unless @product.blank? %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% end %>
<%= text_area_tag :content, '', :placeholder => 'Ask your classmates anything...' %>
<%= hidden_field_tag :user_id, current_user.id %>
<%= submit_tag 'Post', :class => "btn btn-medium btn-primary post-room-button" %>
<% end %>
I have been trying to do this, but I cannot find a way to get it to work. Whenever I submit the form that fails one of the validations in my model, the page simply redirects to my ‘else’ path in my respond_to function in my create controller.
You can remove the compete new method from your controller but not the new view present in the views file.
When you say render action: “new” it renders the new.html.erb file present in the views folder of your app and when you say redirect_to action: “new” it will call the new action of the controller and will perform the operations present in the new action and then render the new.html.erb.
You cannot render the create action as it does not contain any view file and create action as per REST is supported by POST request and not GET request