您的位置:首页 > 大数据 > 人工智能

rails手脚架(scaffold)功能

2016-01-07 00:00 686 查看
scaffold是一个快速开发rails应用的代码框架,可以使用一条命令实现CRUD操作。

1: 创建一个应用

[code] rails new scaffoldapp
 cd scaffoldapp
 rails s


在浏览器中打开http://localhost:3000/

2: 创建一个名为blog的Scaffold

使用rails的scaffold创建模版,在此基础上进行增加、删除、修改、查询(CRUD)操作.

[code]rails g scaffold blog title:string content:text picture:string


数据库迁移:

[code]rake db:migrate


浏览器中访问:http://localhost:3000/blogs



3:添加图片上传功能

可以参考我的上一篇博客rails中使用carrierwave上传图片

更新Gemfile

[code]gem 'carrierwave'
bundle install
rails generate uploader Picture


修改/app/models/blog.rb,挂载picture属性

[code]mount_uploader :picture, PictureUploader


打开 app/views/ideas/_form.html.erb ,找到这一行:

[code]<%= f.text_field :picture %>


将它改成:

[code]<%= f.file_field :picture %>


并将这一行:

[code]<%= form_for(@blog) do |f| %>


改成:

[code]<%= form_for(@blog,:html => {:multipart => true}) do |f| %>


打开 app/views/ideas/show.html.erb 并将

[code]<%= @blog.picture %>


改为

[code]<%= image_tag(@blog.picture_url, :width => 300) if @blog.picture.present? %>


4.修改样式

打开/app/controllers/blogs_controller.rb

新建一个方法

[code] def list
     @blogs = Blog.all
  end


在/app/views/blogs/目录下新建list.html.erb

[code]<div class="bgheader">
    <h1>My Blog</h1>
</div>

<% @blogs.each do |blog| %>
      <h2 class="bgtitle"><%=link_to blog.title,blog %></h2>
      <p><%= blog.content[0,150]%></p>

<% end %>


修改/config/routes.rb,加入:

[code]root 'blogs#list'


增加/app/assets/stylesheets/application.css

[code]body{

    padding: 0px;
    margin:0px;
    width:1000px;
    margin:0 auto;
 }
.bgheader{
    margin-top: -20px;
    height: 80px;
    background-color: #E9F2E8;
}
.bgheader h1{
    color: #238A2A;
    padding-top: 15px;
    padding-left: 20px;
}

.bgtitle a:link,.bgtitle a:visited{
    color: #0080FF;
}
#blog_title{
    width:300px;
    height:20px;
}
#blog_content{
    width:480px;
    height:300px;
}
.bgcontainer{
    width:600px;
}
.bgshow{
    width:800px;
}


修改/app/views/blogs/show.html.erb

[code]<div class="bgshow">
<p id="notice"><%= notice %></p>

<h2>
  <%= @blog.title %>
</h2>
  <%= @blog.content %>
<hr>
  <%= image_tag(@blog.picture_url, :width => 300) if @blog.picture.present? %>
<hr>
<%= link_to 'Edit', edit_blog_path(@blog) %> |
<%= link_to 'Back', blogs_path %>
</div>


效果

首页




详情页


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: