Ruby Rail First Step: Difference between revisions

From Objectif Client Inc
Jump to navigation Jump to search
 
(14 intermediate revisions by the same user not shown)
Line 23: Line 23:
<pre>root :to => "home#index"</pre>
<pre>root :to => "home#index"</pre>


==Start to Work with Resources==
==Start to Work with Model==


===Generate a resource (Post)===
===Generate the first Model (Post)===
<pre>rails generate scaffold Post name:string title:string content:text</pre>
<pre>rails generate scaffold Post name:string title:string content:text</pre>


Line 42: Line 42:
===Add validation===
===Add validation===
*Add validation into app/modles/post.rb
*Add validation into app/modles/post.rb
<pre>class Post < ActiveRecord::Base
<syntaxhighlight lang="ruby">
class Post < ActiveRecord::Base
   validates :name,  :presence => true
   validates :name,  :presence => true
   validates :title, :presence => true,
   validates :title, :presence => true,
                     :length => { :minimum => 5 }
                     :length => { :minimum => 5 }
end
end
</pre>
</syntaxhighlight>
 
===Create an Xml List===
===Create an Xml List===
* Modify the sectioni def index of the file app/controllers/posts_controller.rb
* Modify the sectioni def index of the file app/controllers/posts_controller.rb
Line 62: Line 64:
* Now try [http://localhost:3000/posts.xml http://localhost:3000/posts.xml]
* Now try [http://localhost:3000/posts.xml http://localhost:3000/posts.xml]
* More information at [http://www.railsdebutant.org/fr_guides/active_record_querying.html Active Record Query Interface]
* More information at [http://www.railsdebutant.org/fr_guides/active_record_querying.html Active Record Query Interface]
==Creation Process==
===New Post Request===
* the form is empty but has the same feild a the one used for modification
* Inside the file app/controllers/posts_controller.rb
<pre>  def new
    @post = Post.new
  end
</pre>
===Empty Form===
* app/view/new.html.erb
<pre>
<h1>New post</h1>
<%= render 'form' %>
<%= link_to 'Back', posts_path %>
</pre>
* render 'form' is a partials. A code which can be reused
===Form ===
* app/views/posts/_form.html.erb
<syntaxhighlight lang="ruby">
<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
      <ul>
      <% @post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</syntaxhighlight>
* [http://www.railsdebutant.org/fr_guides/layouts_and_rendering.html#using-partials Layouts and Rendering in Rails]
* form_for is used to create an html form
* form_for is knows the current transaction is an add or an update
* If you are using field not attached to a model you must use form_tag.
===Create Post===
* Inside the file app/controllers/posts_controller.rb
<pre>
def create
  @post = Post.new(params[:post])
  respond_to do |format|
    if @post.save
      format.html { redirect_to(@post,
                    :notice => 'Post was successfully created.') }
      format.xml  { render :xml => @post,
                    :status => :created, :location => @post }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @post.errors,
                    :status => :unprocessable_entity }
    end
  end
end
</pre>
==Add a second Model linked with the first one==
* Instead of using the scaffolding we are proceding peice by peice
* Generate Model
<pre>rails generate model Comment commenter:string body:text post:references</pre>
* Rail has generated the Model: the file app/models/comment.rb
<pre>class Comment < ActiveRecord::Base
  belongs_to :post
end</pre>
* Rail has generated the migration
<pre>rake db:migrate</pre>
===Add Relation to Post===
* Modify post.rb
* add association "has_many"
<pre>
class Post < ActiveRecord::Base
  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
  has_many :comments
end
</pre>
===Add a route ===
* Modify route file config/routes.rb
<pre>
resources :posts do
  resources :comments
end
</pre>
[http://www.railsdebutant.org/fr_guides/routing_outside_in.html Rails Routing from the Outside In]
===Add a controller===
<pre>rails generate controller Comments</pre>

Latest revision as of 17:21, 15 November 2014

  • Your first application with MySQL

Create the Application

rails new firstapp -d mysql
  1. Move into the application directory
cd firstapp
  1. If you setup MySQL or Postgres with a username/password, modify the
  2. config/database.yml file to contain the username/password that you specified
  1. Create the database
rake db:create
  1. Start the server
rails server
  1. Visite the web site

http://localhost:3000

  1. change the default page

Add the following into config/routes.rb

root :to => "home#index"

Start to Work with Model

Generate the first Model (Post)

rails generate scaffold Post name:string title:string content:text

Creating and Customizing Rails Generators & Templates

Create Tables (posts)

rake db:migrate
  • To create in production
rake db:migrate RAILS_ENV=production.

Add a link into the home page

  • Add Post Page in the index file app/view/home/index.html.erb
<%= link_to "My Blog", posts_path %> 

Add validation

  • Add validation into app/modles/post.rb
class Post < ActiveRecord::Base
  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
end

Create an Xml List

  • Modify the sectioni def index of the file app/controllers/posts_controller.rb
def index
  @posts = Post.all
 
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @posts }
  end
end

Creation Process

New Post Request

  • the form is empty but has the same feild a the one used for modification
  • Inside the file app/controllers/posts_controller.rb
  def new
    @post = Post.new
  end

Empty Form

  • app/view/new.html.erb
<h1>New post</h1>
<%= render 'form' %>
<%= link_to 'Back', posts_path %>
  • render 'form' is a partials. A code which can be reused

Form

  • app/views/posts/_form.html.erb
<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
  • form_for is used to create an html form
  • form_for is knows the current transaction is an add or an update
  • If you are using field not attached to a model you must use form_tag.

Create Post

  • Inside the file app/controllers/posts_controller.rb
def create
  @post = Post.new(params[:post])
 
  respond_to do |format|
    if @post.save
      format.html { redirect_to(@post,
                    :notice => 'Post was successfully created.') }
      format.xml  { render :xml => @post,
                    :status => :created, :location => @post }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @post.errors,
                    :status => :unprocessable_entity }
    end
  end
end

Add a second Model linked with the first one

  • Instead of using the scaffolding we are proceding peice by peice
  • Generate Model
rails generate model Comment commenter:string body:text post:references
  • Rail has generated the Model: the file app/models/comment.rb
class Comment < ActiveRecord::Base
  belongs_to :post
end
  • Rail has generated the migration
rake db:migrate

Add Relation to Post

  • Modify post.rb
  • add association "has_many"
class Post < ActiveRecord::Base
  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
 
  has_many :comments
end

Add a route

  • Modify route file config/routes.rb
resources :posts do
  resources :comments
end

Rails Routing from the Outside In

Add a controller

rails generate controller Comments