views:

33

answers:

2

Hi.

I have a validation that needs to be done in controller. If it fails I need to go back to the view action back again with all values populated as it is on the page. Is there a simple way to do that (using incoming params map).

A: 

Depends on the flow of your app, really.

If the validation fails, you could pull the data out fo the database ...

if invalid?
  @model = model.find(:id
end

Otherwise you might need to store the original values in hidden fields in the view and use those.

Toby Hede
If validation fails, the data shouldn't even be in the database. I don't know much about RoR, but it should still be sitting in the `POST` variable, no?
Mark
it's a new record so data has not been persisted to database. Data is coming from the screen and is in params hash. If validation fails at controller level (usually validation in RoR is at model level) the page needs to refresh with same data. Like rendering "new" action again just that with values prepopulated.
Priyank
+4  A: 

This is the basic way all Rails controllers and scaffolds work. Perhaps you should try generating scaffolds?

def create
  @banner_ad = BannerAd.new(params[:banner_ad])
    if @banner_ad.save
      flash[:notice] = 'BannerAd was successfully created.'
      redirect_to :action => "show", :id => @banner_ad
    else
      render :action => "new"
    end
  end
end

I populate a @banner_ad here, attempt to save it, if it fails, I return to the form and the @banner_ad object is available to me. I then need to have a form that uses the Rails form helpers to populate the values from the object.

MattMcKnight