Rails 2.3 uniqueness check - how can I grab the value causing the error
I am trying to capture a value that is throwing a uniqueness error (or, for that matter, any other type of inline validation) to display in an option :message
. Here is what I tried (didn't work)
# inside the model
validate_uniqueness_of :name, :message => "#{name} has already been taken" # also tried using #{:name}
I could use custom validation, but that beats the point of using what's already integrated into AR. Any suggestions? thanks.
a source to share
Try this interpolation technique:
validate_uniqueness_of :name, :message => "%{value} has already been taken"
The RailsGuide for Active Posts and Callbacks shows an example %{value}
interpolating in a custom error message:
:message => "%{value} is not a valid size"
I looked through the documentation validates_each and see that the verification unit transferred three properties: |record, attr, value|
. All three can be accessed with %{model}
, %{attribute}
and %{value}
.
This is limited for now, since it gives you access to three properties, luckily that's all you need.
a source to share
Try self.name
validates_uniqueness_of :name, :message => "#{self.name} has already been taken" # also tried using #{:name}
Also validate_uniqueness_of is not correct , it should be validates_uniqueness_of
If that doesn't work then use validate method and comment line validates_uniqueness_of
def validate
name= User.find_by_name(self.name) #Assuming User is your Model Name
unless name.blank?
self.errors.add :base, "#{self.name} has already been taken"
end
end
a source to share