Forum: Ruby on Rails nil.errors and error_messages_for

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
320b651f98fa44b807d99bd7f4aac40d?d=identicon&s=25 bongoman (Guest)
on 2009-03-26 05:23
(Received via mailing list)
Hi there

I'm wanting to re-render my index action in the event of an object not
getting saved; I use render not redirect so as to preserve the
validation errors.

I'm using the error_messages_for helper in my view but I get a
nil.errors error when I attempt to display the view.

I can avoid this error by setting up @discount = Discount.new in my
index action, but this obliterates the instance variable with the
attached error messages.

I'm chasing my tail on this and any clues would be appreciated.
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2009-03-26 05:37
(Received via mailing list)
bongoman wrote:

>
> I'm chasing my tail on this and any clues would be appreciated.

Hear galloping think horses not zebras, here...

Your action goes like...

  @discount = Discount.new(params[:discount]) # warning use
attr_protected!
  unless @discount.save
    render :action => 'index'
  end

So... uh... @discount indeed contains a stuffed Discount instance with
populated
errors... so what's the problem??

So post your actual action instead of making us guess? (-8
320b651f98fa44b807d99bd7f4aac40d?d=identicon&s=25 bongoman (Guest)
on 2009-03-26 05:57
(Received via mailing list)
> So... uh... @discount indeed contains a stuffed Discount instance
with populated
> errors... so what's the problem??

Well it only does when the index template is rendered AFTER validation
fails. The same action gets invoked prior to the form submission at
which point in time there is no @discount variable, hence the
nil.errors

> So post your actual action instead of making us guess? (-8

Here we go:

    @discount = Discount.find(params[:id])
    if @discount.update_attributes(params[:discount])
      flash[:notice_good] = "Discounts have been updated"
      redirect_to :action=> 'index'
    else
      index # I need to do this in order to get my instance variables
populated for the index view
      render :action => 'index'
    end
Aafa8848c4b764f080b1b31a51eab73d?d=identicon&s=25 Phlip (Guest)
on 2009-03-26 06:12
(Received via mailing list)
> Here we go:
>
>     @discount = Discount.find(params[:id])
>     if @discount.update_attributes(params[:discount])
>       flash[:notice_good] = "Discounts have been updated"
>       redirect_to :action=> 'index'
>     else
>       index # I need to do this in order to get my instance variables
> populated for the index view

and ... index re-populates @discount?

put this inside the index:

   @discount ||= Discount.new
This topic is locked and can not be replied to.