Pundit宝石。有没有办法在yml文件中显示记录的特定属性值?

时间:2017-03-14 13:56:02

标签: ruby-on-rails ruby pundit

我正在玩pundit gem。我需要在短信中显示帖子title

#config/locales/pundit.en.yml

en:
  pundit:
    default: 'You cannot perform this action.'
    post_policy:
      share?: 'You cannot share post %{post.title}!'

控制器:

#posts_controller.rb

def share
  @post = Post.find(params[:id])
  authorize @post
  @post.share
  redirect_to @post
end

我收到的是完全相同的字符串,没有任何错误和替换

You cannot share post %{post.title}!

有什么建议吗?感谢

2 个答案:

答案 0 :(得分:2)

I18n模块无法知道post.title是指@post.title。 Rails通过其表单助手来完成某种魔术,但这种魔法并没有扩展到Pundit。

以下是Pundit的文档suggest customizing your error messages

  

创建自定义错误消息

     

NotAuthorizedError提供有关查询的信息(例如   :create?),什么记录(例如Post的实例),以及什么政策   (例如PostPolicy的实例)导致错误被引发。

     

使用这些queryrecordpolicy属性的一种方法是   将它们与I18n连接以生成错误消息。这是你的方式   可能会这样做。

class ApplicationController < ActionController::Base
  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def user_not_authorized(exception)
    policy_name = exception.policy.class.to_s.underscore

    flash[:error] = t "#{policy_name}.#{exception.query}", scope: "pundit", default: :default
    redirect_to(request.referrer || root_path)
  end
end
     
en:
 pundit:
   default: 'You cannot perform this action.'
   post_policy:
     update?: 'You cannot edit this post!'
     create?: 'You cannot create posts!'
     

当然,这只是一个例子。 Pundit对于如何实现错误消息传递是不可知的。

根据这些信息,我们可以推断出如下内容:

private
def user_not_authorized(exception)
  policy_name = exception.policy.class.to_s.underscore
  interpolations = exception.query == 'share?' ? { title: @post.title } : {}

  flash[:error] = t "#{policy_name}.#{exception.query}", scope: "pundit", default: :default, **interpolations
  redirect_to(request.referrer || root_path)
end

然后,在你的语言环境中:

en:
  pundit:
    default: You cannot perform this action.
    post_policy:
      share?: You cannot share post %{title}!

我没有Pundit的应用程序在我面前所以我无法测试这个;你可能需要稍微细化一下。

答案 1 :(得分:-1)

问题是单(')引号不允许字符串插值只有double(“)引号

取自Programming Ruby

  

双引号字符串(...)可以使用序列#{expr}将任何Ruby表达式的值替换为字符串。如果表达式只是全局变量,类变量或实例变量,则可以省略大括号。