Steve
Steve

Reputation: 592

Validating forms with variables

In most of the examples I see, I notice that in the controller, the new method simply has:

@object = Object.new

In the create method, you'll see something like:

@object = Object.find(params[:object])
    if @object.save
      flash[:success] = "This object has been added."
      redirect_to objects_path
    else
      render :action => 'new'
    end

This works fine, but the only thing I run into (pretty common), is when the validations fail using some built in helper methods:

validates_presence_of :value

the "render :action => 'new' will be called. So then rails bypasses the controller and goes straight to the action for new, which attempts to render the form.

That bypass of the controller kills me, because sometimes I'm loading values into the form using values I've defined in my controller.

I'll end up getting errors because of nil values, because rails bypassed the controller and the values were never set when loading "render :action => 'new'".

My question: What's the best way to redirect a form (or best practice in general) when validating a form that has variables assigned in it that is defined the in controller? I want to avoid those nil value errors, so I'm thinking I'm just doing it wrong to begin with.

Upvotes: 0

Views: 92

Answers (2)

alex.zherdev
alex.zherdev

Reputation: 24164

One way: render hidden fields for all those variables, so your object will already have them in create action. Another way: create a before_filter for those two actions.

Personally I'd go with the second option.

Upvotes: 0

aaronrussell
aaronrussell

Reputation: 9467

You could move your custom bit of code that loads your various values into a before_filter, a bit like:

before_filter :get_values, :only => [:new, :create]

def new
  # your code here
end

def create
  @object = Object.new params[:object
  if @object.save
    flash[:success] = "This object has been added."
    redirect_to objects_path
  else
    render :action => 'new'
  end
end

private

def get_values
  # your code here
end

Upvotes: 1

Related Questions