【问题标题】:.current_user not working when using scopes?.current_user 在使用范围时不起作用?
【发布时间】:2015-02-15 22:46:34
【问题描述】:

我正在使用 Devise 和 has_scope gem 来过滤选项,并且只想显示当前用户的链接。

这行得通

@links = current_user.links.all


这不是。有人可以解释我需要做些什么来完成这项工作吗?

@links = apply_scopes(Link).current_user.all

【问题讨论】:

  • current_user 只是一个返回用户对象的方法,所以你不能像这样调用我,你可以尝试 current_user.apply_scopes(Link).all 但事实上我不确定,只是给它试一试。
  • 试过了,但后来我得到了 apply_scopes 的未定义方法。
  • 这是有道理的,因为 User 模型没有名为 apply_scopes 的实例方法。 ://
  • 一种解决方法是在链接中创建一个接受参数 user_id 的范围,并在控制器中使用 current_user.id 传递该范围的默认值。我不熟悉 has_scope 语法,但从他们的文档来看,从逻辑上讲它肯定会起作用,希望对您有所帮助。
  • 你不会碰巧有一个关于如何做到这一点的例子吗?

标签: ruby-on-rails ruby-on-rails-4 has-scope


【解决方案1】:

一种解决方案是在带有参数 user_id 的链接和不带参数的控制器 has_scope 中创建一个范围,然后将哈希传递给 apply_scopes 方法以覆盖提供的范围值。

链接模型

scope :of_user,->(user_id){ where(user_id: user_id)}

链接控制器

has_scope :of_user

只需调用 apply_scopes(Link, of_user: current_user.id).all 其中 of_user 只是命名范围的应用参数。

【讨论】:

  • 我得到“未定义的局部变量或方法 current_user”
  • 好的,我想通了尝试 apply_scopes(Link, of_user: current_user.id).all 和 has_scope :of_user,如果一切正常(在 rails 3 上测试)我将编辑我的答案,否则我将删除它。
【解决方案2】:

我建议以下模式来申请所有权:

型号

scope :by_owner, ->(user_id) { where(user_id: user_id) }

控制器

has_scope :by_owner, allow_blank: true,
  default: ->(controller){ controller.current_user } do |controller, scope|
    scope.by_owner(controller.current_user.id)
  end

默认情况下应用by_owner 范围。无需为您的操作添加任何其他范围。

一个例子:

def index
  render json: apply_scopes(Link)
end

【讨论】:

    猜你喜欢
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 2015-02-15
    • 2014-06-12
    相关资源
    最近更新 更多