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>