Rails:nil的未定义方法`map':NilClass

时间:2017-05-26 18:57:12

标签: ruby-on-rails

我知道有很多问题有相同的错误,但我找不到任何解决我的问题。所以,我有一个“Bairro”,并且有“Clientes”和“Imoveis”属于。问题是创建一个客户“Cliente”工作正常,但当我去创建一个“Imovel”我有错误:
用于nil的未定义方法`map':NilClass并突出显示:

<%= f.collection_select :bairro_id, @bairros, :id, :nome, {} , class: "form-control" %>

Imovel.rb是这样的:

class Imovel < ApplicationRecord
  belongs_to :bairro
  belongs_to :cliente
end

在控制器中我有这个:

def new
  @imovel = Imovel.new
  @bairros = Bairro.all
  @clientes = Cliente.all
end

def edit
  @bairros = Bairro.all 
  @clientes = Clientes.all 
end

def update
  @bairros = Bairro.all
  respond_to do |format|
    if @imovel.update(imovel_params)
      format.html { redirect_to @imovel}
    else
      format.html { render :edit }
    end
  end
end


def create
    @bairros = Bairro.all
    @imovel = Imovel.new(imovel_params)
    respond_to do |format|
      if @imovel.save
        format.html { redirect_to @imovel}
        format.json { render :show, status: :created, location: @imovel }
      else
        format.html { render :new }
      end
    end
  end

通常在未定义@bairros = Bairro.all时会发生此错误,但在这种情况下不会。

视图打开很好,我可以编辑,但是当我要保存时,错误发生了。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

错误很可能是因为表单在您的更新操作中重新呈现,而您没有在那里设置@bairros

def update
  if object.save
    # works
  else 
    # doesn't work
    @bairros = Bairro.all # or something
    render 'edit'
  end
end

或者如果你重新渲染表格,你也可以

def create
  @bairros = Bairro.all
  if ....