Declare type of instance variable on controller
Asked Answered
I

2

8

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?

Inclined answered 24/10, 2017 at 16:55 Comment(0)
B
9

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.

Bardo answered 24/10, 2017 at 17:31 Comment(0)
M
2

As mentioned using a local variable here is the most elegant solution. For people ending up here with a similar error message but in a different context, read below:

The second error message already points to the right solution, the following code should work too:

class CompanyController < ApplicationController
  @companies : Array(Company)?

  def index
    @companies = Company.all
    render("index.slang")
  end
end
Mountaineering answered 24/10, 2017 at 20:23 Comment(2)
Don't should be Array(Company) ?Pterous
This won't work. First, @companies should be initialized in a constructor or be nillable. Second, Company.all returns Jennifer::QueryBuilder::ModelQuery(Company), not Array(Company). But thanks for explaining the concept.Bardo

© 2022 - 2024 — McMap. All rights reserved.