Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Message Forum: Embellishing the Models - 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: Embellishing the Models - Ruby on Rails

Several methods must be added to the model so that it can be modified from the application.

Embellishing the Models

 

Several methods must be added to the model so that it can be modified from the application. These methods are all defined by ActiveRecord.

 

Message Model

First, we must create an empty Message model by typing ruby script/generate model Message in the Ruby Console. Before we make any change to the model we must create the messages table. Figure 24.28 is the migration that creates the messages table and adds data to it. To run this migration, navigate to the messageboard directory and type rake db:migrate.

 

 

1    # Fig. 24.28: db/migrate/002_create_messages.rb

 

2    # Database migration script modified to add data to the table.

 

3    class CreateMessages < ActiveRecord::Migration

 

4          # create and configure messages table

 

5          def self.up

 

6                 create_table :messages, do |t|

 

7                       t.column :title, :string, :limit => 64

 

8                       t.column :author, :string, :limit => 20

 

9                       t.column :created_on, :timestamp

 

10                      t.column :email, :string, :limit => 40

 

11                      t.column :message, :text

 

12                      t.column :forum_id, :integer

 

13                end # do block

14

15                Message.create :title => "Welcome to the Fourth Edition",

 

16                      :author => "Bob Green",

 

17                      :email => "noone@deitel.com",

 

18                      :message => "We hope you enjoy the book.",

 

19                      :forum_id => 2

 

20         end # method self.up

21

22         # remove messages table

 

23         def self.down

 

24                drop_table :messages

 

25         end # method self.down

 

end # class CreateForums

 

Fig. 24.28 | Database migration script modified to add data to the table.

 

The create_table function call (lines 6–13) specifies the columns of the table. Lines 7–12 create the title, author, created_on, email, message and forum_id columns with appropriate variable types and length limits. Lines 15–20 add data to the table. Rails fills the created_on column value automatically when a new row is created. To apply the migration, type rake db:migrate in the console window.

 

Figure 24.29 shows the Message model that encapsulates the messages table in the database. Line 4 invokes the belongs_to method, which defines an association with the forums table that can be used to access elements of the forums table. This method will allow the Message to access the forum to which the given Message belongs simply by calling a method named forum on the Message. This is known as an association method.

 

Lines 7–9 are examples of validators that can be applied to an object that inherits from ActiveRecord. These validations occur when the save method is called on a message object in an attempt to store it in the database. If the validations are successful, then the object is saved to the database and the method returns true. If the validations fail, an Errors object associated with the Message object is updated and the method returns false. The method validates_presence_of ensures that all of the fields specified by its parameters are not empty. The method validates_format_of matches all of the fields specified by its parameters with a regular expression. The regular expression in line 9 rep-resents a valid e-mail address. This regular expression can be found in the Rails framework documentation at api.rubyonrails.org.

 

 

1    # Fig. 24.29: app/models/message.rb

 

2    # Message Model containing validation and initialization functionality.

 

3    class Message < ActiveRecord::Base

 

4          belongs_to :forum # adds a forum method to Message

5

6          # validators (validates automatically before ActiveRecord.save)

 

7          validates_presence_of :title, :author, :email, :message

 

8          validates_format_of :email,

 

9                 :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

 

10   end # class Message

 

Fig. 24.29 | Message model containing validation and initialization functionality.

 

Forum Model

Next, create an empty forum model by typing in ruby script/generate model forum.

 

Then create the forums table in a similar fashion to messages and users. Figure 24.30 is the Migration that sets up the messages table.

 

The create_table function call (lines 6–10) specifies the columns of the table. Lines 7–9 create the name, administrator and created_on columns with appropriate variable types and length limits. Lines 12–16 add data to the table. To apply the migration, type in rake db:migrate.

 

The model for the forums table (Fig. 24.31) looks similar to the model for the mes-sages table. We can create an association method that allows a Forum to access every Mes-sage that is associated with it. Line 4 shows the has_many method, which will create a method called messages for every Forum object. The messages method will return an array of all the messages in the Forum.

1    # Fig. 24.30 db/migrate/003_create_forums.rb

 

2    # Database migration script modified to add data to the table.

 

3    class CreateForums < ActiveRecord::Migration

 

4          # Create and configure forums table

 

5          def self.up

 

6                 create_table :forums do |t|

 

7                       t.column :name, :string, :limit => 64

 

8                       t.column :administrator, :string, :limit => 20

 

9                       t.column :created_on, :timestamp

 

10                end # do block

11

12                Forum.create :name => "Ruby On Rails",

 

13                      :administrator => "user1"

 

14                Forum.create :name => "Internet and World Wide Web: 4th Edition",

 

15                      :administrator => "user1"

 

16         end # method self.up

17

18         # remove forums table

 

19         def self.down

 

20                drop_table :forums

 

21         end # method self.down

 

22   end # class CreateForums

 

Fig. 24.30 | Database migration script modified to add data to the table.

 

 

1    # Fig. 24.31: app/models/forum.rb

 

2     # Forum model that includes validation and initialization functionality.

 

3    class Forum < ActiveRecord::Base

 

4          has_many :messages, :dependent => :destroy

 

5          validates_presence_of :name

 

6    end # class Forum

 

Fig. 24.31 | Forum model that includes validation and initialization functionality.

 

 

When a forum is deleted, all of that forum’s messages should also be deleted. Line 4 sets the dependent parameter of the has_many method to :destroy to ensure that when a forum is destroyed all the messages that are associated with it are destroyed as well.

 

Generating Scaffold Code

 

Now that the user can log in and out of our application, we need to create the messages and forums views and controllers. Since much of this code is standard CRUD, we can use the Rails scaffold generator by typing ruby script/generate scaffold message and ruby script/generate scaffold forum in the Ruby Console. The scaffold generator creates the scaffold code that would be generated using the scaffold method in the con-troller. When using the scaffold method, notice that the controller name and the view directory are both pluralized forms of the name, rather than the singular form that the model generator and controller generator would create.

 

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


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