0

I'm adding a csv upload feature to my site. I want to be able to add startups to categories that I've created.

I'm getting this error:

error message: note that I've tried both authorize @startup and @startups

Startup_policy.rb file

 class StartupPolicy < CategoryPolicy
      def create?
        user.present?
       end

       def import?
        user.present?
      end
    end

Startup_controller.rb

class StartupsController < ApplicationController
  before_action :authenticate_user!

   def create
    @startup = @startupable.startups.new startup_params
    @startup.user = current_user
    @startup.save
    redirect_to @startupable, notice: "Your startup was added succesfully."
    authorize @startup
   end

   def import
    count = Startup.import params[:file]
    redirect_to category_startups_path, notice: "Imported #{count} startups"
    authorize @startups
   end

   private
   def set_category
    @startup = Startup.find(params[:id])
    authorize @startup
   end 

  def startup_params
    params.require(:startup).permit(:company, :url)
  end
end 

Startup.rb

class Startup < ActiveRecord::Base
    belongs_to :startupable, polymorphic: true
    belongs_to :user

    def self.import(file)
            counter = 0
            CSV.foreach(file.path, headers: true, header_converters: :symbol) do |row|
                startup = Startup.assign_from_row(row)
                if startup.save
                    counter += 1 
                else
                    puts "#{startup.company} - #{startup.errors.full_messages.join(",")}" 
                end 
            end 
        counter
    end

    def self.assign_from_row(row)
        startup = Startup.where(company: row[:company]).first_or_initialize
        startup.assign_attributes row.to_hash.slice(:url)
        startup
    end
end

EDIT: added Category_policy.rb

class CategoryPolicy < ApplicationPolicy
    def index?
        true
    end
    def create?
        user.present?
    end

    def update?
        return true if user.present? && (user.admin? || category.user)
    end

    def show?
        true
    end

    def destroy?
        user.present? && user.admin?
    end
private
    def category
        record
    end
end

What am I missing here? Pundit is pretty easy to use but for some reason I'm stumped on this one.

user3787971
  • 457
  • 4
  • 22

1 Answers1

1

I don't see that you've set @startups anywhere. So it's nil, which explains the error message. I assume you meant to set it to the resulting list you get after importing the CSV. Or, since all you are checking in the policy is whether you have a user, you could just authorize :startup which will get you to the right policy, and not care which startups you have.

Daiku
  • 1,237
  • 11
  • 20