0
我想从错误中数组字段中的消息获取值。从错误中数组的Rails
举例密码字段:
@user.errors.select{|key,msg| key == :password}
这将产生:
{:password=>["Your password and confirmation are not the same"]}
我要的是一个办法只有获得该领域的消息。
我怎样才能做到这一点?
我想从错误中数组字段中的消息获取值。从错误中数组的Rails
举例密码字段:
@user.errors.select{|key,msg| key == :password}
这将产生:
{:password=>["Your password and confirmation are not the same"]}
我要的是一个办法只有获得该领域的消息。
我怎样才能做到这一点?
只需使用@user.errors[:password]
或者您可以使用following methods
hsh.values→阵列 返回填充了来自HSH值的新阵列中的一个。另请参阅哈希#键。
h = { "a" => 100, "b" => 200, "c" => 300 }
h.values #=> [100, 200, 300]
hsh.values_at(键,...)→阵列 返回包含与给定键相关联的值的数组。另请参阅Hash.select。
h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
h.values_at("cow", "cat") #=> ["bovine", "feline"]
编辑:
使用值的方法可以做到这一点
@user.errors.select{|key,msg| key == :password}.values.first
这取决于你所需要的。请记住,任何errors
值本身就是一个数组,因为表单字段可能有不止一个错误。自己与铁轨控制台
> 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"
感谢法比奥试试吧。无论如何要在上面的块中做到这一点。正如@ user.errors.select {|键,味精|密钥==:密码,味精}或其他东西? – chell
@chell更新我的答案,以反映您的评论内容。让我知道。 – Fabio
感谢法比奥它可以作为您发布这么清楚。非常感谢,我会用它。大。 – chell