简体   繁体   中英

Repopulating page with previous values in rails

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM