Rails 4 - Pundit - how to write a scope

こ雲淡風輕ζ 提交于 2019-12-06 11:30:17

The problem is that you aren't actually giving the scope the user id. In this one: User.id this will never work... the User class represents all users... it doesn't make any sense to ask for the id of it (you'll just get back the id of the ruby-object that stores the class methods).

in the other one... you use user.id but don't actually set the value of the user variable (so it will always fail).

Maybe try actually passing the relevant user id into the method as a parameter eg:

# define the `user` parameter as an argument to this scope-method
scope :projects_for_user, -> (user){ joins(:user_id).where('project.profile.user_id = ?', user.id) }

def resolve
  if user.has_role?(:admin)
    scope.all
  elsif user.id == @project.profile.user_id
    scope.projects_for_user(user) # pass the user into the method
  elsif user.present?
    scope.in_state(:publish)
  else 
    Project.none  
  end
end

Note: I have not (and will not) test this code, it may have typos or bugs... give it a go and fix the bugs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!