Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Message Forum: Forum Controller and Forum Views - Ruby on Rails

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - Ruby on Rails

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Message Forum: Forum Controller and Forum Views - Ruby on Rails

The ForumsController (Fig. 24.32), which was initially generated as part of the scaffolding, handles all incoming requests from the client.

Forum Controller and Forum Views

 

The ForumsController (Fig. 24.32), which was initially generated as part of the scaffolding, handles all incoming requests from the client. The index, list, new, and delete methods are all responsible for rendering a view, while the create and destroy methods are responsible for processing incoming data and then redirecting to another action. We will not use the edit or show methods so you may delete the .rhtml view files associated with them.

 

The verify method call in lines 4–5 is edited scaffold code, which ensures a post request is used to send data to the server for each request that modifies the database. Whenever a method modifies a database, the arguments should be from a post so that they don’t show up in the URL. The :only argument specifies which actions this verification should be applied (create and destroy in this case). If a call to create or destroy is not made via a post request, line 5 redirects the request to the list action.

 

 

1    # Fig. 24.32: app/controllers/forums_controller.rb

 

2    # ForumsController implements CRUD functionality.

 

3    class ForumsController < ApplicationController

 

4          verify :method => :post, :only => [ :destroy, :create ],

 

5                 :redirect_to => { :action => :list }

6

7          # shortcut to the list method

 

8          def index

 

9                 list

 

10               render :action => 'list'

 

11         end # method index

12

13         # set up the list web page that lists all forums

 

14         def list

 

15               @forums = Forum.find( :all )

 

16         end # method list

17

18         # set up the new web page that adds a new forum

 

19         def new

 

20               if ( session[ :user ] == nil ) # if user is not logged in

 

21                       flash[ :error ] = 'you must be logged in to complete this action'

 

22                      redirect_to :action => "index" and return

 

23               end # if

24

25               @forum = Forum.new

 

 

25         end # method new

27

28         # attempt to create a new forum with the parameters passed in

 

29         def create

 

30               @forum = Forum.new( params[ :forum ] )

 

31               @forum.administrator = session[ :user ].name

32

33               if @forum.save # if save method was successful

 

34                      flash[ :notice ] = 'Forum was successfully created.'

 

redirect_to :action => 'list'

36                else # save was unsuccessful

 

37                      render :action => 'new' # go to new

 

38                end # if...else

 

39         end # method create

40

41         # set up the delete web page

 

42         def delete

 

43                if ( session[ :user ] == nil ) # if user is not logged in

 

44                       flash[ :error ] = 'you must be logged in to complete this action'

 

45                      redirect_to :action => "index" and return

46                else

 

47                      @forums = Forum.find( :all,

48                            :conditions => "administrator = '#{ session[:user].name }'" )

 

49                end # if else

 

50         end # method delete

51

52         # delete a forum with a specified parameter

 

53         def destroy

 

54                # find the forum and delete it

 

55                Forum.destroy( params[ :forum ][ :id ] ) # delete the forum

 

56                redirect_to :action => 'list' # redirect to list

 

57         end # method destroy

 

58   end # class ForumsController

 

Fig. 24.32 | ForumsController implements CRUD functionality.

Method index (line 8–11) redirects the client to the list method (lines 14–16), which obtains a list of forums from the database to be displayed on the page. The new method (lines 19–26) checks whether the user has privileges to create a new forum. If not, lines 21–22 display an error and redirect the user to the index action. The hash called flash in line 21 is used to display messages in the view. Flash is a special type of session storage that is always automatically cleared after every request to the controller. If the user has privileges, line 25 creates a new instance of the forum object which is initialized with data from the user input.

 

The create method (lines 29–39) is similar to the scaffold code, but differs in that the administrator attribute of the forum being saved must be the name of the user who is logged in. Line 33 attempts to save the forum, and either renders a template if the method returns false (line 37), or redirects to the list method and updates the flash object if the method returns true (lines 34–35). The delete method (lines 42–50) sets up the dele-tion operation by finding all the forums created by the user currently logged in. Once the user picks a forum to delete in the view, the destroy method (lines 53–58) destroys the forum specified by the user (line 55) and re-displays the list (line 56).

 

List View

Figure 24.33 is the template that is rendered by the list method from the Forum control-ler. [Note: We replaced the auto-generated list.rhtml from the scaffolding]. This is also the template rendered by the index method. Line 10 uses the link_to method to create a link with the name of the forum and the list action of its messages, which we build in Section 24.6.5.. Lines 12–13 contain a conditional statement which make the forum ital-icized for five minutes after it has been created by using the minutes.ago method of the

1    <!-- Fig. 24.33: app/views/forums/list.rhtml -->

 

2    <!-- Template for the list action that displays a list of forums. -->

 

3    <h1>Deitel Message Forums</h1>

 

4    <h2>Available Forums</h2>

 

5    <ul>

 

6          <% for forum in @forums %>

 

7          <!-- create a list item for every forum -->

 

8                 <li>

 

9                       <!-- link to list action in messages -->

 

<%= link_to ( forum.name, {:controller => 'messages',

11     :action => 'list', :forum_id =>  forum.id},

12     { :class => (forum.created_on <       5.minutes.ago ?

13                            'recent': nil ) } ) %>

 

14                </li>

 

15         <% end %> <!-- end for -->

 

16   </ul>

  

13   <% if ( session[ :user ] ) then %>

 

14         <!-- a user is logged in -->

 

15         <h2>Forum Management</h2>

16         <ul>

 

17                <li><%= link_to 'Add a Forum', :action => 'new' %></li>

 

18                <li><%= link_to 'Delete a Forum', :action => 'delete' %></li>

 

19         </ul>

 

<% end %> <!-- end if -->


Fig. 24.33 | Template for the list action that displays a list of forums.

 

Fixnum class. The if statement in lines 17–24 displays the XHTML in lines 19–23 only if there is a user logged in.

 

New View

Figure 24.34 shows the template for the Forum controller’s new method. This is code gen-erated by the scaffold. Lines 4–7 create a form that is rendered to the page, and indicate

 

1    <!-- Fig. 24.34 app/views/forums/new.rhtml -->

 

2    <!-- Template for a new action that adds a forum to the forums table. -->

 

3    <h1>New forum</h1>

 

4    <% form_tag :action => 'create' do %>

 

5          <%= render :partial => 'form' %>

 

6          <%= submit_tag "Create" %>

 

7    <% end %>

8

9  <%= link_to 'Back', :action => 'list' %>

 

Fig. 24.34 | Template for a new action that adds a forum to the forums table.

 that the action create will be called when the Create button is pressed. This template ren-ders a partial—a block of HTML and embedded Ruby code stored in another file and in-serted directly into the document. A partial allows the same block of code to be used across multiple documents. In this example, line 5 renders the partial named form, which inserts the file _form.rhtml at that line of code. A partial filename always begins with an under-score.

 

Line 6 uses the submit_tag method to create a submit button that when clicked will create a Hash with the form’s fields as keys and the user’s input as values. Line 9 uses the link_to function to allow the user to go back to the forums list by redirecting the client to the list action of the forum controller.

 

The partial in Fig. 24.35 renders the input text field for the form. The administrator and created_on fields will be generated on the server, so they’ve been deleted from the scaffold’s code. The created_on field will be automatically set to the time when the forum is created. The administrator field will be set by the controller.

 

1    <!-- Fig. 24.35: app/views/forums/_form.rhtml -->

 

2    <!-- Partial that contains a form used to add a new forum. -->

 

3    <%= error_messages_for 'forum' %>

 

4    <p><label for="forum_name">Name</label><br/>

 

<%= text_field 'forum', 'name'  %></p>



Delete View

The delete view (Fig. 24.36) is not generated by the scaffold, so we create it ourselves. It is similar to create in that it renders a form, but uses the collection_select method to display for that administrator the list of available forums to delete. The collection_select takes five parameters—the type of object to be selected, the field which the options are to be grouped by, the collection from that to obtain the list of ob-jects, the field that will be sent once an option is selected and the field that is to be dis-played on the screen for each option.

 

 

1    <!-- Fig. 24.36: app/views/forums/delete.rhtml -->

 

2    <!-- Template for delete action used to delete a Forum. -->

 

3    <h1>Delete a Forum</h1><br />

4

5  <% form_tag  :action => :destroy do %> <!-- create from tag -->

 

6          <p><label for="forum_id">Forum Name</label><br />

 

7          <%= collection_select "forum", "id", @forums, "id", "name" %></p>

 

8          <%= submit_tag "Delete" %> <!-- create submit tag -->

 

9    <% end %> <!-- create end form tag -->

10

10  <%= link_to 'Back', :action => 'list' %> <!-- link back to list method -->


Forum Layout

Figure 24.37 is the layout that renders every template for the ForumsController. It has all the necessary XHTML, and contains the login/logout text (lines 13–25). Line 29 auto-matically renders the template of any action that uses the template.

 

1    <?xml version = "1.0" encoding = "utf-8"?>

 

2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4              

5    <!-- Fig. 24.37: app/views/layouts/forums.rhtml -->

6    <!-- Layout that displays the logged-in user for every Forums action. -->

7    <html xmlns = "http://www.w3.org/1999/xhtml">

 

8    <head>

 

9          <title>Forums: <%= controller.action_name %></title>

 

10         <%= stylesheet_link_tag 'scaffold' %> <!-- link to a stylesheet -->

 

11   </head>

 

12   <body>

 

13         <div style = "text-align: right">

 

14                <% if ( session[ :user ] ) then %> <!-- if user is logged on -->

 

15                      <!-- code to display if user is logged on -->

 

16                      <%= "Logged In As #{ session[ :user ].name }: " %>

 

17                      <%= link_to 'Log Out',

18                            :controller => 'users', :action => 'logout' %>

 

19                <% else %> <!-- user is not logged on -->

 

20                      <!-- code to display if user is not logged on -->

 

21                      <%= "Not Currently Logged In:" %>

 

22                      <%= link_to 'Log In',

23                            :controller => 'users', :action => 'admin' %>

 

24                <% end %> <!-- end if -->

 

25         </div>

 

26         <p style="color: green"><%= flash[ :notice ] %></p>

 

27         <p style="color: red"><%= flash[ :error ] %></p>

28

29         <%= yield %> <!-- displays template -->

 

30   </body>

 

31   </html>

 

Fig. 24.37 | Layout that displays the logged-in user for every Forums action.

If the user is logged in (line 14), lines 16–18 display the username on the page and use the link_to method to enable the user to log out by redirecting to the logout action. Otherwise, lines 21–23 allow the user to log in, using the link_to helper method to redi-rect the user to the admin action. Lines 26–27 display any error messages or success mes-sages that result from user interactions.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.