[Question] How to show models attributes' value in validation message?

Say I have a model with a validation in User model like this:

Class User < ActiveRecord::Base
validates_uniqueness_of :name,
:message=>“user has already exist!”
end

As you can see, I want to write my own error message for this
validation.
And I get this error message in Controller like this:

Class Login < ActiveController::Base
def create_user
begin
@user = User.new(:name=>params[:name])
@user.save!
rescue
if @user.errors.blank?
flash.now[:notice_err] = “Database error!”
else
temp = []
@user.errors.each{|err| temmp << err[1]}
flash.now[:notice_err] = “

  • ”+temp.join("
  • ")+"</
    li>
"
end
else
flash.now[:notice] = “
  • User #{params[:name]} created!</
    li>

end
end
end

Everything goes on well for now.
However, if I want to show the ‘error user name’ in the validation
message like this

Class User < ActiveRecord::Base
validates_uniqueness_of :name,
:message=>“user #{self.name} has already
exist!”
end

It cannot pass, and the following error shows out:

undefined method ‘name’ in model

So my question is “How can I get the value of attributes in a model
validation helper?”
Are there anyone having any idea on this?

boblu wrote:

Class User < ActiveRecord::Base
validates_uniqueness_of :name,
:message=>“user #{self.name} has already
exist!”
end

It cannot pass, and the following error shows out:
undefined method ‘name’ in model

:message=>"user #{name} has already
or
:message=>"user #{attributes[:name] || @name} has already
or
write your own validation method

Thank you for your reply.
I have tried two of what your suggested.

":message=>"user #{name} has already " shows “user has already”
the #{name} will just be skipped though I had set a value in the model
object.

":message=>“user #{@name} has already” shows error message “@name not
defined”

I will try this
:message=>"user #{attributes[:name]} has already
and I will tell you the result here.

Anyway, thank you.

On Oct 2, 3:42 pm, Pokkai D. [email protected]