Thursday, May 24, 2012

[Rails] Re: Errors and flash[:error]

On May 24, 10:18 am, "Miguel A." <li...@ruby-forum.com> wrote:
> > I provide a form, of sorts, for creating HABTM relationships between
> > two other models.
>
> Not sure if I understand your issue, but I believe you are looking at
> nested resources and nested forms.
>

Thanks Miguel, I realize my question wasn't clear. Some of the details
I provided are unnecessary. The important parts are:
1. My controller has a create action that verifies the current user
has permissions to create this specific record. I'm reporting errors
to this verification via flash[:error].
2. The model being created has it's own validation to ensure that only
valid records are saved. I'm reporting errors to this validation via
the errors object.

My inexperienced RoR question is: how do I consolidate errors from
both sources (controller and model validation) and report back to the
user?

> > I'd like to provide a bullet list of the combined results of
> > validation errors and session matching errors.
>
> Rails can do this automatically for you if you generate a scaffolding.
> But if you are looking for going through the created hash for the
> message, take a look at:http://railscasts.com/episodes/18-looping-through-flash
>

Great suggestion, I didn't realize this would be wired up by default
in scaffolding. I created a new project and think I can now answer my
own question. A form partial was generated, and it will display all of
the error messages in the errors object:

<div id="error_explanation">
<h2><%= pluralize(@stuff.errors.count, "error") %> prohibited
this stuff from being saved:</h2>

<ul>
<% @stuff.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>

The generated views do not show anything from flash[:error]
(furthermore flash[:error] is not the means of showing model
validation errors). So I guess the obvious answer to my question is to
use a variation that shows both:

<% if @stuff.errors.any? or !flash[:error].blank?%>
<div id="error_explanation">
<ul>
<% @stuff.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
<% unless flash[:error].blank? %>
<li><%= flash[:error] %></li>
<% end %>
</ul>
</div>
<% end %>

Does this approach look reasonable? I'm mildly concerned that rails
doesn't offer a convenient way to combine the data. That hints that I
might be doing things a bit unconventionally.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate