快速创建一个简单博客的框架

1.创建项目

rails new blog
  

 2.创建数据库

cd blog
rails g scaffold Post title:string user:string content:text
rails g scaffold Comment body:text user:string post:references
rake db:migrate
 

 3.指定主页

config/routes.rb中增加

root :to => 'posts#index'

删除public中的index.html文件


4.postcomment两张表关联起来

app/model/post.rb

has_many :comments, :dependent => :destroy 

app/model/comment.rb

belongs_to :post

 config/routes.rb

resources :comments
resources :posts

 修改为:

resources :posts do
resources :comments, :only => [:create, :index]
end
resources :comments

 这样修改后可以在post页面中追加若干个comments


5.增加限制

model/post.rb

validates_uniqueness_of :title                           #不允许重复
validates_presence_of :title, :content, :user    #不允许为空

 Model/comment.rb中

validates_presence_of :post, :body, :user

 

6.增加commentnewedit页面中的post的下拉选择框

将app/views/comments/_form.html.erb

<div class="field">
  <%= f.label :post %><br />
  <%= f.text_field :post %>
</div>

 改为

<div class="field">
  <%= f.label :post %><br />
  <%= f.collection_select :post_id, Post.all, :id, :title %>
</div> 

7.给文章增加评论功能

App/posts/show.html.erb中追加

<% unless @post.comments.empty? %>
  <div id="comments">
    <h3>Comments (<%= @post.comments.length %>)</h3>
    <% @post.comments.each do |comment| %>
      <%= comment.user %>&nbsp;say:
      <%= simple_format(comment.body) %>
    <% end %>
  </div>
<% end %>

<%= form_for [@post, Comment.new] do |f| %>
  <div id="comments">
    <h3>New Comment</h3>
    <p>
      <%= f.label :user %><br />
      <%= f.text_field :user %>
    </p>
    <p>
      <%= f.label :body %><br />
      <%= f.text_area :body, :rows => 10 %>
    </p>
    <%= f.hidden_field :post_id, :value => @post.id %>
    <p><%= f.submit "Add Comment" %></p>
  </div>
<% end %>


8.修改comment页面中post的显示

indexshow页面中的comment.post改为comment.post.title


9.修改追加comment后的跳转

Controllers/comments_controller.rb

create函数中的创建成功后的跳转改到所在的postshow页面中

def create
  @comment = Comment.new(params[:comment])

  respond_to do |format|
    if @comment.save
      format.html { redirect_to @comment.post, notice: 'Comment was successfully created.' }
      format.json { render json: @comment, status: :created, location: @comment }
    else
      format.html { render action: "new" }
      format.json { render json: @comment.errors, status: :unprocessable_entity }
    end
  end
end
  

10.给文章的题目增加链接

1

<td><%= post.title %></td>改为

<td><%= link_to post.title, post %></td>

2

<td><%= comment.post.title %></td>改为

<td><%= link_to comment.post.title, comment.post %></td>


11.增加创建和修改post的简单权限(在创建、修改或删除前需要先登录)

Controllers/posts_controller.rb

before_filter :authenticate, :except => [:index, :show]

private
def authenticate
  authenticate_or_request_with_http_basic do |name, password|
    name == "admin" && password == "password"
  end
end

你可能感兴趣的:(Rails)