Rails 4 - Pundit - create policy

前端 未结 2 1564
粉色の甜心
粉色の甜心 2021-01-27 09:42

I\'m trying to figure out how to use pundit in my Rails 4 app.

I have a profile view in which I want to display a link to create a new project, subject to pundit authori

相关标签:
2条回答
  • 2021-01-27 09:54

    Usually I will use another class, say ViewPolicy, for the purpose in view:

    class ViewPolicy < Struct.new(:user, :views)
    
        def items_index?
            user.has_role?(:sales)
        end
    
    end
    

    So I can do something like this:

    <% if policy(:views).items_index? %>
      <%= link_to("Items", items_path) %>
    <% end %>
    

    very similar to @Kieran Andrews

    0 讨论(0)
  • 2021-01-27 10:10

    It looks like your code may not have the necessary instance variables. Inside your show method you should have a @project - you can use Pundit to check wether the user can create it.

    As you dont appear to have a @project, you can try this instead:

    <% if policy(Project.new).create? %>
    

    You could also try using a symbol instead:

    policy(:project)
    
    <% if policy(:dashboard).show? %>
      <%= link_to 'Dashboard', dashboard_path %>
    <% end %>
    

    Do you have a policy defined like so?

    # app/policies/project_policy.rb
    class ProjectPolicy < Struct.new(:user, :project)
      # ...
    end
    
    0 讨论(0)
提交回复
热议问题