首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

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

2012-08-25 
快速创建一个简单博客的框架1.创建项目rails new blog???2.创建数据库cd blograils g scaffold Post title

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

1.创建项目

rails new blog
??

?2.创建数据库

cd blograils g scaffold Post title:string user:string content:textrails g scaffold Comment body:text user:string post:referencesrake db:migrate
?

?3.指定主页

config/routes.rb中增加

root:to => 'posts#index'

删除public中的index.html文件


4.将post和comment两张表关联起来

app/model/post.rb中

has_many :comments, :dependent => :destroy?

app/model/comment.rb中

belongs_to :post

?config/routes.rb将

resources :commentsresources :posts

?修改为:

resources :posts doresources :comments, :only => [:create, :index]endresources :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.增加comment的new和edit页面中的post的下拉选择框

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

<div name="code"><div name="code"><% 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的显示

将index和show页面中的comment.post改为comment.post.title


9.修改追加comment后的跳转

Controllers/comments_controller.rb

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

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  endend
??

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]privatedef authenticate  authenticate_or_request_with_http_basic do |name, password|    name == "admin" && password == "password"  endend

热点排行