1.model
- 生成数据库迁移文件,运行db:rake ,db:migrate
class CreateBlogs < ActiveRecord::Migration[6.0]
def change
create_table :blogs do |t|
t.string :title
t.text :content
t.boolean :is_public, default: true
t.belongs_to :user
t.timestamps null: false
end
add_index :blogs, [:user_id]
end
end
- model
class Blog < ApplicationRecord
validates :title, presence: {message: "标题不能为空"}
validates :content, presence: {message: "内容已存在"}
belongs_to :user
end
class User < ApplicationRecord
validates :username, presence: {message: "用户名不能为空"}
validates :username, uniqueness: {message: "用户名已存在"}
validates :password, presence: {message: "密码不能为空"}
validates :password, length: {minimum: 6, message: "密码长度最短为6位"}
has_many :blogs
end
2 controller
class BlogsController < ApplicationController
layout false
before_action :auth_user, except: [:index,:show]
def index
@blogs = Blog.page(params[:page] || 1).per_page(params[:per_page] || 10).order('id desc')
end
def new
@blog = Blog.new
end
def create
@blog = Blog.new(blog_attrs)
@blog.user = current_user # @blog.user_id = current_user.id
if @blog.save
flash[:notice] = '博客创建成功'
redirect_to blogs_path
else
flash[:notice] = '博客创建失败'
render action: :new
end
end
def show
@blog = Blog.find_by params[:id]
end
private
def blog_attrs
params.require(:blog).permit(:title, :content)
end
end
3.view
- index.html
<h1>博客列表</h1>
<%= link_to '创建博客', new_blog_path, method: "post" %>
<table>
<tr>
<th>博客标题</th>
<th>博客作者</th>
<th>博客内容</th>
</tr>
<% @blogs.each do |blog| %>
<tr>
<td><%= link_to blog.title, blog_path(blog) %></td>
<td><%= blog.user.username %></td>
<td><%= blog.content %></td>
</tr>
<% end -%>
</table>
<%= will_paginate @blogs %>
- new.htmml
<h1> 写博客</h1>
<%= form_for @blog, url: blogs_path, method: :post do |f| %>
<% @blog.errors.messages.values.flatten.each do |error| %>
<%= error %>
<% end -%>
<%= f.text_field :title, placeholder: "标题" %>
<%= f.text_area :content, placeholder: "内容" %>
<%= f.submit "创建" %>
<% end -%>
- show.html
<h1><%=@blog.title %></h1>
<p>博客作者</p>
<%=@blog.user.username %>
<p>博客内容</p>
<%=@blog.content %>
ps:基于前几篇博客创建的user,session等