Tuesday, June 23, 2009

Workshop 5:Part B: The active view: passing data from an action too a view

  1. Create a new application called scenery in the same projects directory to demonstrate the use of an active view. > rails scenery > cd scenery
  2. Complete
  3. Create a controller called Demo in scenery\app\controllers scenery> ruby script/generate controller Demo
  4. Complete

  5. Add an action to demo_controller.rb as the method called rubycobe class DemoController< ApplicationController def rubycode end end
  6. Complete
  7. Add a view template - scenery\app\views\demo\rubycode.rhtml We will edit this view in later steps but you may like to add your own test HTML code to the view at this stage.
  8. Complete
  9. Save and restart the Web server and navigate to http://localhost:3000/scenery/rubycode
  10. If I was to follow the script blindly then one of two things will happen here.
    • I have made a mistake or
    • the workshop script is wrong

    If I navigate to the url
    ../scenery/rubycode
    I get the error Routing Error.
    However if I do the logical thing and navigate to
    ../demo/rubycode
    then I get my expected page returned.
  11. Use the Time.now example to pass data from an action to a view.

  12. Modify and save the rubycode action with a value for the time instance variable in the DemoController class in app\controllers\demo_controller.rb class DemoController< ApplicationController def rubycode @time_now = Time.now end end
  13. Done that
  14. Then modify and save the corresponding view template in \app\views\demo\rubycode.rhtml by adding a call by reference to the action’s instance variable: <_br> The time is <_%= @time.now %_> <_br>
  15. Obviously this piece of code is wrong. We should be using the variable defined in the controller @time_now
  16. Restart the Web server and navigate the browser to http://localhost:3000/demo/rubycode Data has been passed from the action to the view as it is done with SQL requests. The instance variables of a Ruby class are available to view templates by referencing the action’s instance variables by name in the view .rhtml template.
  17. The output and the code files are shown below

No comments:

Post a Comment