在控制器上声明实例变量的类型

Osm*_*ond 8 crystal-lang amber-framework

我和Jennifer.cr在Amber框架上有一个水晶项目,我在我的控制器上收到了这个错误:

Can't infer the type of instance variable '@companies' of CompanyController
@companies = Company.all
Run Code Online (Sandbox Code Playgroud)

控制器是:

class CompanyController < ApplicationController
  def index
    @companies = Company.all
    render("index.slang")
  end
end
Run Code Online (Sandbox Code Playgroud)

当我尝试以这种方式解决问题时:

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

我有另一个错误:

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
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个"简单"问题?

Vit*_*upt 9

您不必在此处使用实例变量.局部变量是Amber应用程序默认使用的一种方式(并且可以在视图中访问它们):

class CompanyController < ApplicationController
  def index
    companies = Company.all
    render("index.slang")
  end
end
Run Code Online (Sandbox Code Playgroud)

但是如果由于某种原因想要使用实例变量,则需要在类级别声明和初始化它,或者遵循其他类型的推理规则.