Search code examples
ruby-on-railsruby-on-rails-4pundit

Pundit throws undefined method `user'


I cannot restrict the Project model view to a owning user. Cannot figure this one out:

Error:

undefined method `user' for #<Project::ActiveRecord_Relation:0x007f94b25dd010>

project_policy.rb

class ProjectPolicy < ApplicationPolicy
  def show?
    user.present? && user == record.user
  end
end

Projects controller

class ProjectsController < ApplicationController

  def show
    @project = Project.find(params[:id])
    @pages = @project.pages
    authorize @projects
  end

If I remove the user == record.user all works fine

application_policy file is default

Project belongs to User User has many Projects

project.user in the console works fine.


Solution

  • undefined method `user' for Project::ActiveRecord_Relation:0x007f94b25dd010

    Firstly, I'd assume that @projects is defined somewhere in your code using a before_filter and also I assume its returning a collection of records. If so then here is the issue

    user.present? && user == record.user
    

    Here the record in record.user will be a collection of records not a single record. So record.user just fails with that error.

    Changing authorize @projects to authorize @project should solve your problem