I'm using Devise and has_scope gem for filtering options and only want show a current users links only.
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.
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.
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. No need to add any additional scopes to your action.
An example:
def index
render json: apply_scopes(Link)
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.