主页

在个人博客中增加置顶功能

2023-08-11 03:21PM

1. 在articles表中增加 is_top列,运行命令

bundle exec rails generate migration add_is_top_to_articles

2. 然后打开创建好的文件,在里面增加

class AddIsTopAritcles < ActiveRecord::Migration
   def change
     add_column :articles, :is_top, :boolean, default: false, comment: '默认不置顶,后期自己选择是否置顶'
   end
end

3. 打开编辑/新建页面(app/views/articles/_form.html.erb)

 <div>
      <%= form.label :'是否置顶' %>
      <%= form.check_box :is_top %>
</div>

4. 打开app/controller/articles_controller.rb文件,增加下面的内容

def  index

    # 找到指定的 articles, migration, is_top 默认 false, 修改之后是 true

    @top_articles = Article.where('is_top = ?', true).order('created_at desc') 

  # 找到普通的 articles

    @articles = Article.all

end

 

def   create

     @article.is_top = params[:article][:is_top]

end

def  update

     @article.is_top = params[:article][:is_top]

end

 

 def article_params

    params.require(:article).permit(:title, :content, :category_id, :is_top)

end

 增加完上面几个步骤,个人博客中的置顶功能就完成了

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论