Controllers and Views in Rails:

This post is long overdue! We learned about Controllers and Views last week.

If you do something like this to make a new controller: rails g controller products index new

this is what’s called rendering by default what this means is that the method will attempt to load a view by the same name of the method (Rails automatically creates a view when you create methods in the Controller). The only way to prevent this behavior from happening is to render another view or redirect to another method.

To render another view: Specify using ‘render filename’ or ‘render folder/filename’ – if it’s in a different view folder. If a user registers to your page and the registration failed, then you want to render a page, this allows the page to display an error message and doesn’t save anything to the database. Rendering allows the error message to be displayed in an @instance_variable to display the view page.

The second option is redirect_to: redirects the browser to another controller/method…sends another HTTP request. redirects_to doesn’t actually load another view, it calls another controller/method to render a view. Use redirect_to when a user logs into your site and redirect them to another page because you don’t want to submit an HTTP request.

After a render and redirect_to: the code after those statements are ran.

render: works the same as var_dump and die() that we used in PHP

Passing variable to the view in Rails: Just put an @symbol in front of the variable name in the Controller that you want to make available in the View.

I completed a few assignments to day: All were pretty simple – straight the point. Most notably the Random Name Generator and the Survey Form all which we have done before in different languages so once you’ve seen it once, it’s pretty easy to tackle. Plus, these assignments are merely to get our feet wet in the language and be comfortable assigning instance variables, session data and flash data plus being about to show information in the views.