Search code examples
crystal-langamber-framework

Declare type of instance variable on controller


I have a crystal-lang project on Amber framework with Jennifer.cr and I'm getting this error on my controller:

Can't infer the type of instance variable '@companies' of CompanyController
@companies = Company.all

The controller is:

class CompanyController < ApplicationController
  def index
    @companies = Company.all
    render("index.slang")
  end
end

When I try to solve the problem this way:

class CompanyController < ApplicationController
  def index
    @companies : Array(Company) = Company.all
    render("index.slang")
  end
end

I got another error:

instantiating 'CompanyController#index()'
in src/controllers/company_controller.cr:7: declaring the type of an instance variable must be done at the class level

    @companies : Array(Company) = Company.all

How can I solve this "easy" problem?


Solution

  • You don't have to use instance variable here. Local variable is a way Amber app uses by default (and they are accessible in views):

    class CompanyController < ApplicationController
      def index
        companies = Company.all
        render("index.slang")
      end
    end
    

    But if you want to use an instance variable due to some reason, you need to declare and initialize it at a class level or follow other type inference rules.