QwertyX
QwertyX

Reputation:

Validation error messages

I have two models, frontend and user with respective controllers and views.

From a form_for in frontend view I'm calling a create method in user controller and I save new user in database. All works.

The problem comes with validation. If something is wrong with the model validators I need error messages to be displayed on frontend view... so, I need that if there are errors, when I redirect_to frontend (since render seems not possible for different controller) is possible to display errors here.

I haven't found solutions for this.

Thanks!

Upvotes: 0

Views: 513

Answers (3)

Eric
Eric

Reputation: 766

Quite simple again, in itself. With the method that your form_for calls, let's say it's called def create (within your users controller).

def create @user = User.new(params[:user])
 @user.save
 if [email protected]?
   @failed = true
 end
 respond_to do |format|
   format.js {} # Will render the create.js.rjs file
 end
end

##### create.js.rjs #####

if @failed
 display the errors
else
 do whatever you wish here
end

Upvotes: 0

Eric
Eric

Reputation: 766

If I may, you are going about it wrong. cite has the right idea with doing a render partial.

Let's say that you are calling your frontend from the root of the application, with the registration page all laid out there. In the controller method that has this view, create an instance variable of your user that is then used in the form. For example...

def some_method_for_the_root
    @user = User.new
end

Then in your view

all your code for the view
render :partial => '/users/new'

Within that partial, have your form_for the @user object. Voila, you have a user object that can be used on your main app, and then if the validation fails, it would be best to either update via ajax, or direct the user to a page to explicitly show them the errors.

This is all just from my experience, but it's generally the method I have seen done most often.

Upvotes: 1

cite
cite

Reputation: 778

If you use redirect_to, the validation information on that particular object will get lost. You can try playing cheap shots with saving the object in the flash or the session, retrieving it in the frontend controller (creating an instance variable) and have it validated again, so that the error_messages helper has something to work with.

OTOH, that approach seems flawed. Why not create the form for a new user in the user controller?

Upvotes: 0

Related Questions