Search code examples
ruby-on-railspundit

Rails 4 Pundit - policies in parent models


I'm trying to use rails 4 with pundit policies.

I have a profile model and a projects model. Projects are HABTM with profiles.

I have a project policy, that has a create? action (set to true).

In my profile show page, I want to allow users to create new projects, if they project policy create action allows it.

<% if policy(@project).create? %>
  <%= link_to 'CREATE A PROJECT', new_project_path, :class=>"btn btn-info"  %>
<% end %>

When I try this, i get a nil policy error. Is it because you can't use project actions inside profile views? If so, how do I fix it so that I can display a new project button on my profile show page?


Solution

  • You can use ProjectPolicy.new(current_user, @project).create? to specific ProjectPolicy.

    However, like @miler350 said, @project might be nil. (for example: User has no project created). Make sure your ProjectPolicy#create? handles nil properly.