samedi 25 novembre 2017

Save Model errors to flash Rails 5

I want to add hash with model errors to flash and after that redirect. This is the controller:

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

This is the view:

<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>

With byebug, if I fill in inputs with invalid data and type in the console flash[:errors], I see this output hash:

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

If I add in the view instead <span><%=flash[:errors][:first_name]%></span>, but :

<%=flash[:errors]%>

I see the same hash as a string in 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>

How can I add and use hash with flash messages in Rails 5 ?

Aucun commentaire:

Enregistrer un commentaire