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

阅读更多

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

<%= f.label :post %>
<%= f.text_field :post %>

 改为

<%= f.label :post %>
<%= f.collection_select :post_id, Post.all, :id, :title %>
 

7.给文章增加评论功能

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

<% unless @post.comments.empty? %>
  

Comments (<%= @post.comments.length %>)

<% @post.comments.each do |comment| %> <%= comment.user %> say: <%= simple_format(comment.body) %> <% end %>
<% end %> <%= form_for [@post, Comment.new] do |f| %>

New Comment

<%= f.label :user %>
<%= f.text_field :user %>

<%= f.label :body %>
<%= f.text_area :body, :rows => 10 %>

<%= f.hidden_field :post_id, :value => @post.id %>

<%= f.submit "Add Comment" %>

<% 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

<%= post.title %>改为

<%= link_to post.title, post %>

2

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

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


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
  • blog.rar (264.2 KB)
  • 下载次数: 1

你可能感兴趣的:(rails)