profile for Kells1986 at Stack Overflow, Q&A for professional and enthusiast programmers

Tuesday, 24 September 2013

Write Your First Rails 4 App

I've recently been trying to learn Ruby on Rails, as I've got an idea for an app that I'd like to develop. I completed the excellent Rails for Zombies series of tutorials, this gave me a good grasp of models, controllers, views and routes, however I wasn't sure how to stick all these things together from scratch.

After a lot of Googling I managed to put together the steps required to make a "Hello World" type app. I think a lot of tutorials have been made obsolete by updates to Rails, but this one will work as long as you're using Rails version 4.

The first step is to install Rails. I used Ruby Version Manager to install Rails on my Mac, there are pretty good instructions on that website to get up and running quickly.

We're going to make a really simple website where anyone can come along and write a message, and all the messages that have been left can be read.

To generate a new app - which we're calling message_list - run the following command: rails new message_list. This will create a directory called message_list, next you should cd message_list, and then rails server.

If you point your browser to localhost:3000 you should see a Rails test page if everything has worked properly. If there are any problems at this stage it's probably best to got back to the RVM page and check your installation.

Now we make our model, it's going to be called a message. We do this by typing rails g model message. This will make us the following files: app/models/message.rb and db/migrate/<date>_create_messages.rb.

Next, edit db/migrate/*_create_messages.rb file, to look like this:

class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|

        t.string :name
        t.string :content

      t.timestamps
    end
  end
end

Now we need to build the database, cd to the top directory of the app, and type:

rake db:create
rake db:migrate

Run rails console and then run these commands:

mes = Message.new
mes.attributes={ :name => "James", :content => "This is a test"}
mes.save
exit

Now edit app/models/message.rb so it looks like this:

class Message < ActiveRecord::Base

        validates :name, :presence => true;
        validates :content, :presence => true;

end

Now you're done with the model we need view and controllers. To get these we run this command from the top directory of the app:

rails g controller messages

Next, edit app/controllers/messages_controller.rb. We're going to add functions index - for showing all the messages and new and create for writing new messages. These functions should of course have corresponding view files, which we'll get to later.

Here is what messages_controller.rb should look like:

class MessagesController < ApplicationController

        def index
                @posts = Message.all
        end

        def new
                @message = Message.new 
        end

        def create
                @message = Message.new(mess_params)
                @message.save
                redirect_to '/'
        end

       def show
                @mess=Message.find(params[:id])

                respond_to do |format|
                        format.html
                end               

        end

 private
 def mess_params
    params.require(:message).permit(:name, :content)
   end
end

We also have to add an additional function to permit the the create function to access the parameters necessary to formulate a message. Apparently this is new to Rails 4.

Now the Model and Controller is in place, let's write the views.

We need two files, app/views/messages/index.html.erb and app/views/messages/new.html.erb. In index.html.erb we need the following:

<html>
<h1>Leave A Message!</h1>
<%= link_to "New Message", new_message_path %>
<h1>All Posts:</h1>
<table>
<tr>
        <th>Name</th>
        <th>Post</th>

<% @posts.each do |post| %>
<tr>
        <td><%= post.name %></td>
        <td><%= post.content %></td>
</tr>
        <% end %>
</table>
</html> 

And in new.html.erb we need this:

<html>
<%= form_for :message, url: messages_path do |f| %>
  <p>
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :Message %><br>
    <%= f.text_area :content %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>
</html>

So we have Models, Controllers and Views, now we just need Routes to complete the app. In config/routes.rb we need to add the following:

root :to => "messages#index"
resources :messages

Now you have a complete Rails app, run rails server and go to localhost:3000. You should see the message that we wrote before on the console. There will also be a link to write a new message. Click that link, write out a message and click submit, and you should go back to the list of messages and see your message!

Hopefully that's brought a few things together and you can see how to pull together the theory you learnt to build an app from scratch.

No comments:

Post a Comment