custom validations with acts
Hi I am working on a Rails 3 project and I am using acts-as-taggable-on and everything works perfectly! :)
I just have one question.
Does anyone know how I can add my 'custom' validation to ActsAsTaggableOn::Tag? Any callbacks I can hook into (eg before_tag_save)? or something similar?
I need to run a regex on each 'tag' (to ensure that each tag does not contain any illegal characters) in my tag_list before I save my model and would like to know if there is a standard way of doing it.
The way I solved the problem is by adding a validation method in my PostController which just iterates over the list of Tags and runs the regex, but this seems ugly to me.
Any suggestions?
Thank you in advance! :)
I used two ways in the past. One via a custom validator, another with a validates call.
Custom Validation method
In your model, setup the following
validate :validate_tag
def validate_tag
tag_list.each do |tag|
# This will only accept two character alphanumeric entry such as A1, B2, C3. The alpha character has to precede the numeric.
errors.add(:tag_list, "Please enter the code in the right format") unless tag =~ /^[A-Z][0-9]$/
end
end
Obviously you will need to replace the validation logic and the error message text with something more appropriate in your circumstance.
Keep in mind that in this scenario you can evaluate each tag as a string.
Standard Validation Method
Include this in your model
validates :tag_list, :format => { :with => /^([A-Z][0-9],?s?)*$/,
:message => "Just too awesomezz" }
With this method, you will have to keep in mind that you are validating the entire array that looks like a string. For this reason, you will need to allow for commas and white spaces between the tags.
Choose whichever method suits you most
You could do it in your model with a before_save
callback. There you can manipulate the (let's say) Post's tags before they are saved in the database.
Also you can rewrite tag method on User model:
def tag(taggable, opts = {})
return unless user.have? taggable.article
super
end
it can be useful if user can tag only same article (article :has_many users)
链接地址: http://www.djcxy.com/p/36004.html下一篇: 自定义验证与行为