Links | ? |
Part 2 / 3 : The ControllerKeat | urlon Mon Sep 13 20:59:00 SGT 2004 The Rails new_controller script would've generated something like the following: require 'abstract_application' require 'forum_helper' class ForumController < AbstractApplicationController include ForumHelper endFor our purpose, we'll need to change a few things:
require 'abstract_application' require 'forum_helper' require 'post' require 'comment' class ForumController < AbstractApplicationController include ForumHelper scaffold :post scaffold :comment, :suffix => true def show # when showing a Post, i need to retrieve all the comments too # thus @post and @comments is populated here. sqlId = ForumController.quote(@params["id"]) @post = Post.find(@params["id"]); @comments = Comment.find_all "post_id = #{sqlId}" # after populating our variables, we'll call scaffold to render # using the 'show.rhtml' render_scaffold end def list_comment # default action "list_comment" will show all the comments in # the database, doesn't make sense in our app - so redirect to # the list topics screen list end def list # The 'type' column is automagically used by Rails.. when inserting # a comment, it put 'Comment' as its 'type' value # Hence, to get all the topics, we'll get the 'type is null'.. @posts = Post.find_all "type is null order by created_at desc limit 30" render_scaffold end # Java programmers, this is a static / class function # Putting this function here because I still haven't learnt to # use Rails / ActiveRecord for this purpose.. def ForumController.quote(value) case value when String then "'#{value.gsub(/\\/,'\&\&').gsub(/'/, "''")}'" # ' (for ruby-mode) when NilClass then "NULL" when Float, Fixnum, Date then "'#{value.to_s}'" when Time, DateTime then "'#{value.strftime("%Y-%m-%d %H:%M:%S")}'" else "'#{value.to_yaml}'" end end endIf you're ready. We'll move on to the 'view' portion of the MVC pattern. |