如何拥有一个用户只能在 Rails 的 Ruby 有限时间内编辑帖子的博客

How To Have A Blog Where Users Can Only Edit Posts For A Limited Time in Ruby on Rails

我制作了一个非常简单的博客,用户可以在其中创建、编辑和删除帖子,但是我想添加用户只能在有限时间(比如 3 天)内编辑的功能。我对 Ruby 的理解不够强,不知道如何执行此操作,因此不胜感激。

这是我的笔记(我的帖子名称)控制器

class NotesController < ApplicationController
before_action :find_note, only: [:show, :edit, :update, :destroy]


def index
    @notes = Note.where(user_id: current_user)
end

def show
end

def new
    @note = current_user.notes.build
end

def create
    @note = current_user.notes.build(note_params)

    if @note.save
        redirect_to @note
    else
        render 'new'
    end
end

def edit

end

def update
    if @note.update(note_params)
        redirect_to @note
    else
        render 'edit'
    end
end

def destroy
    @note.destroy
    redirect_to notes_path
end

private

def find_note
    @note = Note.find(params[:id])
end

def note_params
    params.require(:note).permit(:title, :content)
end



end

我假设我需要在编辑方法的某处编写一条规则,以将编辑帖子的能力限制为仅 3 天,以某种方式使用 created_at 功能?我只是不知道该怎么做。

感谢任何帮助。

完美的解决方案是:before_filter

class NotesController < ApplicationController
    before_filter :check_time!, only: [:edit, :update]

    def edit
    end

    def create
    end

    private

    def check_time!
      if Time.now() > @note.created_at + 3.days
        flash[:danger] = 'Out of 3 days'
        redirect_to note_path(@note)
      end
    end
end