Josh Moore
Josh Moore

Reputation: 13548

restful rails model validation

I am working on a rails application (I have some experience with rails). But, this time I am using RESTful to build it. I am wondering how do I validate my models in a RESTful fashion? What I mean by that is when a user enters data into a form, but the model validations prevent the model from being created what is a RESTful way to redirect the user back to the new action with the data they entered still present in the form?

Upvotes: 2

Views: 1356

Answers (4)

Tim Knight
Tim Knight

Reputation: 8356

Josh - you mention wanting to know how to redirect the user back to create if it errored out. If you are use to earlier versions of Rails just make sure you are using the form_for helper rather then the start_form_tag from early. Your controller code will look pretty similar to how you might be used to... for example (a Customer model):

def create
  @customer = Customer.new(params[:customer])
  if @customer.save
    flash[:notice] = 'Customer was successfully created.'
    redirect_to(@customer)
  else
    render :action => "new"
  end
end

You'll notice now the redirect_to(@customer) that forwards to the record that was created in the transaction. But on failure it's the same old render :action.

Upvotes: 3

edthix
edthix

Reputation: 1752

use the scaffold generator to view the example codes on restful controllers

Upvotes: 0

CJ Bryan
CJ Bryan

Reputation: 178

REST only affects your controllers and routes!

Model validations in a RESTful Rails app are the same as the validations in any other Rails app.

Upvotes: 4

Hates_
Hates_

Reputation: 68691

Whether developing in a RESTful or regular fashion, the backend implementation remains generally the same. Just as in a non-RESTful app, you would simply re-render the create page with the form with the instance the user is trying to create. Really with REST, all you are doing is creating a uniform set of URLs which respond to different HTTP requests, everything else remains the same.

Upvotes: 0

Related Questions