Rails 5: error passing time_ago_in_words from controller to view

Viewed 632

I want to prevent users from deleting comments that are more than X minutes old. (This is determined by a status field.) I anticipate that the value of X may change in future so it's currently defined in an initializer:

AGE = 1.minute 

What's the best way to pass the error message from the Comment controller to the (Server-generated Javascript Response) view?

if @comment.status == "locked"
  render "comments/too-old", locals: {message: "You can't delete this comment now as it's more than #{time_ago_in_words(AGE.ago)} old."}
end

This currently fails as we're not allowed to use time_ago_in_words in a controller:

undefined method `time_ago_in_words'

1 Answers

The method time_ago_in_words is from ActionView::Helpers::DateHelper helper which will be automatically included in views.

If you need to access this method from controller then, you need to include this helper in the controller.

Assuming the controller name is CommentsController and action name as destroy:

include ActionView::Helpers::DateHelper

class CommentsController < ApplicationController
  def destroy
    ...
    if @comment.status == "locked"
      render "comments/too-old", locals: {message: "You can't delete this comment now as it's more than #{time_ago_in_words(AGE.ago)} old."}
    end
    ...
  end   
end
Related