Muflix
Muflix

Reputation: 6798

Rails: Displaying controller added error messages

Im creating new product in controller action like this

product = Product.new
    product.name = params['name']
    if params['quantity']=="" then product.errors.add(:base, "Quantity must be filled") end


    if !product.save
     @product = product
     render "index"
    end

And im viewing errors like that

<% @product.errors.each do |attr, msg| %>
          <li> <%= msg %></li>
<% end %>

all errors display but only :base error does not display. How can i display them ?

The quantity column is not part of product model.

(solution) working code:

product.valid? 
if params['quantity']=="" then product.errors.add(:base, "error") end
if product.errors.any?
      @product = product
      render "index"
      return
else
      product.save

Upvotes: 1

Views: 2029

Answers (1)

BroiSatse
BroiSatse

Reputation: 44715

That's not gona work, as rails removes everything from errors just before running validations. Save is running validations, so your custom error is removed.

I personaly believe it is wrong to make any validations inside the controller. But if you really want to do that try:

product = Product.new(name: params[:name])
product.valid?
product.errors.add(:base, "Quantity must be filled") if params['quantity'].blank? then

if product.errors.any? || !product.save(false)
 @product = product
 render "index"
end

However this is most likely a bad idea. If quantity has anything to do with a product model, it should be validated by model. If not, it should not be added to models.errors.

You should probably try doing sth like:

product = Product.new(name: params[:name])
if params[:quantity].blank? || !product.save
 @product = product
 flash[:error] = "Quantity must be filled" unless params[:quantity]
 render "index"
end

and then add some code to handle flash[:error] in your view.

Upvotes: 1

Related Questions