[英].current_user not working when using scopes?
I'm using Devise and has_scope gem for filtering options and only want show a current users links only. 我正在使用Devise和has_scope gem作为过滤选项,只希望仅显示当前用户链接。
This works 这有效
@links = current_user.links.all
This does not. 这不是。 Can someone explain what i need to do to make this work? 有人可以解释我需要做些什么才能使这项工作吗?
@links = apply_scopes(Link).current_user.all
One solution is to create a scope in the link that takes an argument user_id and in your controller has_scope with no arguments, and just pass a hash to apply_scopes method to override the supplied values of your scope. 一种解决方案是在带有参数user_id的链接中创建范围,并在不带参数的控制器has_scope中创建范围,然后将哈希传递给apply_scopes方法以覆盖范围的提供值。
scope :of_user,->(user_id){ where(user_id: user_id)}
has_scope :of_user
Just call apply_scopes(Link, of_user: current_user.id).all where of_user is just the applied params for the named scope. 只需调用apply_scopes(Link,of_user:current_user.id) .all即可,其中of_user只是命名作用域的应用参数。
I suggest the following pattern to apply for ownership: 我建议采用以下模式申请所有权:
Model 模型
scope :by_owner, ->(user_id) { where(user_id: user_id) }
Controller 控制者
has_scope :by_owner, allow_blank: true,
default: ->(controller){ controller.current_user } do |controller, scope|
scope.by_owner(controller.current_user.id)
end
The by_owner
scope is applied by default. 默认情况下将应用by_owner
范围。 No need to add any additional scopes to your action. 无需在操作中添加任何其他范围。
An example: 一个例子:
def index
render json: apply_scopes(Link)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.