denniss
denniss

Reputation: 17589

errors get deleted when set inside model

I have a before_create callback that sets an error inside an object.

class Animal < ActiveRecord:base
   #omitted code
   def check_animal_has_non_poisoned_food
      if self.food.non_poisoned_food.nil?
        self.errors[:non_poisoned_food] = "Animal has non poisoned food"
        return false
      end
   end
end

for some reason, inside the controller, when I do an update attribute, although it fails validation

if animal.update_attributes(params[:animal])
  #ommitted
else
  #goes here
  ap animal.errors //empty
end

there is no error inside the animal.errors

Upvotes: 0

Views: 47

Answers (1)

tadman
tadman

Reputation: 211600

I don't see anywhere in there that you're adding an error. Typically that looks like this:

self.errors.add("Animal has non poisoned food")

Adding it to the attributes isn't going to render it as an error even if you return false to break the create chain.

Upvotes: 1

Related Questions