簡體   English   中英

如何在 Ruby on Rails 中創建一個用戶只能在有限時間內編輯帖子的博客

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

我制作了一個非常簡單的博客,用戶可以在其中創建、編輯和刪除帖子,但是我想添加用戶只能在有限時間(例如 3 天)內進行編輯的功能。 我對 Ruby 的理解不夠強,無法知道如何做到這一點,因此感謝任何幫助。

這是我的 Notes(我的 Posts 名稱)控制器

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

我假設在編輯方法的某個地方我需要編寫一個規則,以某種方式使用 created_at 函數將編輯帖子的能力限制為只有 3 天? 我只是不知如何做到這一點。

任何幫助表示贊賞。

完美的解決方案是: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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM