use rails 3.2.5 version
build project:
rails new {project_name} -d mysql
running rails server:
script/rails server -p 80
the first form:
add route in config/routes.rb
root :to => "posts#new"
//set the home page
get "posts/new"
//a new route that only responds to GET requests,
--------------------------------------------------------------------------------------------------------
script/rails generate controller post new //"new" is the method name
vi app/views/posts/new/html.erb //add the following code
<%= form_for :post, :url => { :action => :create } do |f| %>
//:url => { :action => :create } set post action
<p>
<%= f.label :title %> <br>
<%= f.text_field :title %>
</p>
<p> <%= f.label :text %> <br>
<%= f.text_area :text %>
</p>
<p> <%= f.submit %> </p>
<% end %>
--------------------------------------------------------------------------------------------------------
vi config/routes.rb
//add following post route
post "posts/create"
--------------------------------------------------------------------------------------------------------
vi app/controllers/posts_controller.rb //add method create
class
PostsController < ApplicationController
def
new
end
def
create
#render :text => params[:post].inspect
//The render method here is taking a very simple hash with a key of text and value of params[:post].inspect
@post = Post.new(params[:post])
@post.save
redirect_to :action => :show, :id => @post.id
//save data to database
end
def
show
@post
= Post.find(params[
:id
])
end
end
--------------------------------------------------------------------------------------------------------
rails generate model Post title:string text:text //create the post model
//this command will create a database structure file
//app/models/post.rb anddb/migrate/20120419084633_create_posts.rb
(name could be a bit different)
--------------------------------------------------------------------------------------------------------
rake db:migrate
//Rails will execute this migration commond and tell you it created the post table
//Because you’re working in the development environment by default
//If the production environment you must explicitly pass it when invoking the commond
//rake db:migrate RAILS_ENV=production.
Open config/routes.rb and add the following route:
get
"posts/:id"
=>
"posts#show"
open app/view/posts/show.html.erb and add the following content:
<
p
>
<
strong
>Title:</
strong
>
<%=
@post
.title
%>
</
p
>
<
p
>
<
strong
>Text:</
strong
>
<%=
@post
.text
%>
</
p
>
5.8 Listing all posts
http://edgeguides.rubyonrails.org/getting_started.html
to be continued......