如何限制用户可以在 Rails 中编辑记录的时间?

How do I restrict how long a user can edit a record in Rails?

我正在制作一个类似博客的网站,用户可以在其中 post 注释,我想限制他们在 post 之后的前 3 天只能编辑 posts ing,我遇到了麻烦。

我的笔记控制器中有以下代码

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

def edit
end

def create
end

private

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

我有一个 post 已经 1 天了,出于测试目的,我在 check_time 中使用小时而不是天!我的代码中的方法来查看它是否有效,但它没有。出于某种原因,如果我从 > 更改为 < 但是它确实有效。

我确定我已使用以下迁移将 created_at 时间戳附加到我的笔记中:

class AddTimestampsToNote < ActiveRecord::Migration[5.0]
def change_table 
add_column(:notes, :created_at, :datetime) 
add_column(:notes, :updated_at, :datetime) 
end 
end

我真的不确定为什么这不起作用,所以任何帮助将不胜感激

您的代码如下:

if @note.created_at > @note.created_at + 3.hours

这个说法永远不会成立 (x !> x + 3)。也许你的意思是:

Time.now > @note.created_at + 3.hours

改用自定义验证。

class Note < ApplicationRecord 
  # ...
  validate :is_editable, unless: :new_record?

  private 
  def is_editable
    if @note.created_at > 3.days.ago
      errors[:created_at] = "can't be edited after 3 days."
    end
  end
end