get values from errors array Rails
I want to get the message from the errors array for a field.
Example for the password field:
@user.errors.select{|key,msg| key == :password}
This produces:
{:password=>["Your password and confirmation are not the same"]}
What I want is a way to just 开发者_C百科get the message for the field.
How can I do this?
Just use @user.errors[:password]
Alternatively you can use one of the following methods
hsh.values → array Returns a new array populated with the values from hsh. See also Hash#keys.
h = { "a" => 100, "b" => 200, "c" => 300 }
h.values #=> [100, 200, 300]
hsh.values_at(key, ...) → array Return an array containing the values associated with the given keys. Also see Hash.select.
h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
h.values_at("cow", "cat") #=> ["bovine", "feline"]
edit:
Using the values method you could do this
@user.errors.select{|key,msg| key == :password}.values.first
It depends on what you need. Keep in mind that any errors
value is an array itself because a form field could have more than one error. Try it yourself with rails console
> pry
pry(main)> {:password=>["Your password and confirmation are not the same"]}
=> {:password=>["Your password and confirmation are not the same"]}
pry(main)> {:password=>["Your password and confirmation are not the same"]}.values
=> [["Your password and confirmation are not the same"]]
pry(main)> {:password=>["Your password and confirmation are not the same"]}.values.first
=> ["Your password and confirmation are not the same"]
pry(main)> {:password=>["Your password and confirmation are not the same"]}.values.first.first
=> "Your password and confirmation are not the same"
精彩评论