Custom Validations with a Model: failing on save
I am not f开发者_如何学Goinding any great examples online and so am asking an easy question for what I expect will get an easy answer. Be gentle. :)
I have a Post model.
p = Post.find(1)
p.title = "This is the Title of this Article"
p.url_title = "this-is-the-title-of-this-article--created-by-user-name"
When the Post is created, I create the :url_title based off the title. This is how I key off it in the database rather than exposing IDs which are also boring and non-descriptive.
I build this :url_title in a before_save so that is why I can't simply use 'validates_uniqueness_of' because it looks like the validations are done before the before_save kicks in and there is a :url_title to validate.
So, I need to ensure that :url_title is unique. I append the "--created-by-#{p.user.name}" to allow for there to be multiple uses of the same title from different users.
So, what I need to do is have a custom validation that confirms that :url_title is unique to the database before saving and, if it is not unique, raises and error and informs the user.
Thoughts on the best way to do this? '
You can move your callback from before_save
to before_validation
(see here). This callback will be run on create and update action, so I think it will be sufficient for your needs.
Use this to create the url_title
before_validation_on_create :create_url_title
....
private
def create_url_title
url_title = .....
end
Then add the proper validation to url_title
validate_uniqueness_of :url_title, :message => "This title is taken, please choose a different title"
Just add
validates_uniqueness_of :url_title
in your Post model
精彩评论