rails项目(六)——博客发布与查看

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等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值