1.3. Model and Controller

As always use the generate script to create the model and the controller :

  %: script/generate model Message
  %: script/generate controller message

Open the app/controller/application.rb file and add the following line in the class :

layout 'application', :except => :new_message_ajax

This line tells rails to use the application layout for every actions except for new_message_ajax. You can have more than one layout free action, just use an array :

 :except => [:new_message_ajax, :foo42]
.

Copy and past the code below in the message controller.


class MessageController < ApplicationController

    # this one is used by the ajax thing
    def new_with_ajax
        message = Message.new(@params['message'])
        if message.save
            # get the new collection
            @messages = Message.find_all
            # render the page content
            render 'message/message_list'
        end
    end

    # this one list all the messages
    def list
        @messages = Message.find_all
    end

    # this one creates a planet
    def destroy
        # find the message
        Message.find(@params['id']).destroy
        # get the new collection
        @messages = Message.find_all
        # render the page content
        render 'message/message_list'
    end

end

To make something nicer and to show you some usefull things we are going to use a layout and a small css.

Create the app/views/layout/application.rhtml file and paste the following code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15">

<title>ajax</title><link rel="stylesheet" type="text/css" href="/stylesheets/style.css" title="Style">
<meta http-equiv="Content-Language" content="fr">
<meta name="ROBOTS" content="ALL">
<meta http-equiv="imagetoolbar" content="no">
<%= javascript_include_tag "prototype" %>
</head>

<body>

<%= @content_for_layout %>    

</body>
</html>


Now the css, create the public/stylesheets/style.css file and paste it the following lines :

.message {
    margin: 1em;
    border: 1px solid #CCC;
    padding: 1em;
    background: #EEE;
}
.message h3 {
    margin: 0;
    padding: 0;
}

.author {
    float: right;
    font-style: italic;
    margin-right: 3em;
}

It’s not really usefull but it makes things nicer.