1

我想添加与模型错误的散列闪存和重定向后。这是控制器:保存模型错误到闪存Rails 5

def update 
    current_user.update_attributes(user_params) 
    if current_user.errors.any? 
     flash.keep[:errors] = current_user.errors.messages 
    end 
    byebug 
    redirect_to edit_path 
end 

这是视图:

<div> 
    <%=f.text_field :fname, placeholder: 'First Name', limit:50 %> 
     <span><%=flash[:errors][:first_name]%></span> 
</div> 

<div> 
    <%=f.text_field :lname, placeholder: 'Lirst Name', limit:50 %> 
    <span><%=flash[:errors][:last_name]%></span> 
</div> 

随着byebug,如果我填写与在控制台flash[:errors]无效数据和类型的输入,我看到这个输出散列:

{:first_name => [“名字必须是最小1个字符”,“无效”],:last_name => [“太短(最小为1个字符)”,“无效”]}

如果我的观点,而不是<span><%=flash[:errors][:first_name]%></span>增加,但:

<%=flash[:errors]%> 

我看到了相同的散列在HTML的字符串:

<span> 
    {"first_name"=>["First name must be minimum 1 character", "is invalid"], 
    "last_name"=>["is too short (minimum is 1 character)", "is invalid"]} 
</span> 

如何添加和使用带闪光灯的消息哈希在Rails 5中?

+0

散列键错误是否存储'current_user.errors.messages' ?,其中的问题em,当在视图中显示内容时,是否需要显示它们? –

+0

嗨,它存储它们,是的。如果我用byebug键入控制台,我会看到错误为'flash [:errors]'或'current_user.errors.messages'的散列并不重要。他们输出相同的结果(散列错误)。问题是,在视图中,如果我使用'<%= flash [:errors] [:last_name]'它是空的,但是如果我在控制台中进行调试,它不是空的。但是,如果我使用'<%= flash [:errors]',它会显示带有霍尔错误的整个哈希值,但是会显示为字符串。 – gdfgdfg

+0

在你输出的最后一个例子中,它将changint从符号到字符串的哈希键,你可以检查你可以以字符串的方式访问它们吗? '<(%)=闪光[:错误] [ '如first_name']%>'? –

回答

1

当你的哈希正在从符号键改变:

{ :first_name => ..., :last_name => ... } 

到字符串键:

{ "first_name" => ..., "last_name" => ... } 

那么你可以尝试访问这些字符串,而不是像现在一样,你这样做以相反的方式,如:

<span> 
    <%= flash[:errors]['first_name'] %> 
</span>