2

when we have validate_presence_of :name in the model and then when we put in the create action that we re-render 'new', then the form_for will populate the fields, and error_messages_for 'story' will have the correct error message.

this is really great, and and the same time, this looks like magic... i found that many books don't explain how the magic occur. is it by some global variable?

when the form_for is called... is it using the @story that came back from the @story.save, instead of the @story = Story.new from the new action? so if i use :story for the form_for, the fields won't be populated on error?

sometimes i feel that i am playing magic when using Ruby on Rails, except I don't know how the magic happens... kind of like if I make the rabbit appear, but I don't know how I did it. So I really want to know the inner workings of Rails.

1 Answer 1

6

Yes, Rails is very magical. Unfortunately these are just things that you have to learn to live with, and once you get used to the conventions you get to use the magic to do some very complicated things with great ease.

There are three separate issues here that are relatively simple individually but look very magical when you take it all in at once. Let's break them down one by one:

When validations fail, they disallow the model object from being saved and add errors to the object.errors hash.

When you run @story.save, it kicks off all the validations. Since @story.name is blank, validates_presence_of :name adds an error to the object.

Instance variables in the controller are available to the views they render.

So, yes, it is the same @story that the view has access to - the one that is invalid and has error information attached to it.

form_for takes many forms, and the one you're using is very smart

The form_for tag in your view probably looks like this:

<%= form_for @story do |story| =>

This is a special version of form_for that infers all kinds of information from the object passed in and renders the form appropriately. @story has some of its fields populated because of the line

@story = params[:story]

in your controller, so it goes ahead and fills in those fields for you. It does some other things, too - for example, it checks @story.new_record? to see if it should use the POST HTTP method (RESTful create) or the PUT method (RESTful update).

In summary, there are lots of little bits of magic to learn, but once you do the big magic is much easier to understand. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.