Ruby on rails 如何限制用户在Rails中编辑记录的时间?

Ruby on rails 如何限制用户在Rails中编辑记录的时间?,ruby-on-rails,edit,Ruby On Rails,Edit,我正在创建一个类似博客的网站,用户可以在其中发布注释,我想限制他们只能在发布后的前3天内编辑帖子,但我遇到了麻烦 我的notes控制器中有以下代码 class NotesController < ApplicationController before_filter :check_time!, only: [:edit, :update] def edit end def create end private def check_time! if @note.created_a

我正在创建一个类似博客的网站,用户可以在其中发布注释,我想限制他们只能在发布后的前3天内编辑帖子,但我遇到了麻烦

我的notes控制器中有以下代码

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
class NotesController@note.created_在+3.6小时
闪光[:危险]=“三天内”
重定向到注释路径(@note)
结束
结束
结束
我有一篇1天的帖子,出于测试的目的,我用了几个小时而不是几天的检查时间!方法来查看它是否工作,但它不工作。但是,由于某种原因,如果我从>改为<,它确实有效

我确信我已使用以下迁移将创建的时间戳附加到我的笔记上:

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

我真的不知道为什么这不起作用,因此,如果您能提供任何帮助,我们将不胜感激。

您的代码包含以下内容:

if @note.created_at > @note.created_at + 3.hours
这句话永远不会正确(x!>x+3)。也许你的意思是:

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

您的代码包含以下内容:

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
课堂笔记3.days.ago
错误[:created_at]=“3天后无法编辑。”
结束
结束
结束

改用自定义验证

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
课堂笔记3.days.ago
错误[:created_at]=“3天后无法编辑。”
结束
结束
结束

我认为您在这里的条件是反向的,但除此之外,这绝对是解决问题的方法。谢谢@Glyoko。FixedI尝试了此操作,但出现以下错误:NotesController的未定义方法“validate”:类您将验证添加到您的模型中,而不是控制器。我认为您的条件在这里是反向的,但除此之外,这绝对是执行此操作的方法。谢谢@Glyoko。FixedI尝试了此操作,但出现以下错误:NotesController的未定义方法“validate”:类您将验证添加到模型中,而不是控制器。