Reputation: 38012
I have a model with before_create
and before_update
callbacks that can return false
. The model is NOT saved when the callbacks fail (as expected), however my controller redirects to the index path on the model not being created (as opposed to rendering the new template). My code is:
class Person
before_create :reversify
before_update :reversify
def reversify
return false if self.name.blank?
self.name = self.name.reverse
end
end
class PeopleController < ApplicationController
respond_to :html
def new
@person = Person.new
respond_with(@person)
end
def create
@person = Person.create(params[:person])
respond_with(@person)
end
end
Upvotes: 0
Views: 587
Reputation: 9605
respond_with
uses the presence / absence of @person.errors
to determine the appropriate RESTful response.
I'm going to theorise that because you're relying on using failing callbacks to prevent saving invalid objects, ActiveRecord isn't populating @person.errors
, which results in ActionController::Responder
determining that the save was successful.
I suggest re-writing your Person class to use a validation:
class Person
before_save :reversify
validates :name, :presence => true
def reversify
self.name.reverse!
end
end
Upvotes: 2