2017-05-26 133 views
-2

我知道有很多問題有相同的錯誤,但我沒有找到任何解決我的問題的方法。所以,我有一個「Bairro」,有屬於的「Clientes」和「Imoveis」。問題是,建立一個客戶「Cliente」工作得很好,但是當我去創造一個「Imovel」我有錯誤:
未定義的方法'地圖」的零:NilClass和突出顯示:Rails:未定義的方法`map'for nil: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

錯誤很可能是因爲表單在您的更新操作中重新呈現,並且您沒有在那裏設置@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 .... 
+0

我更新方法我有這樣的:def更新 @bairros = Bairro.all 的respond_to做|格式| if @ imovel.update(imovel_params) format.html {redirect_to @imovel} else format.html {render:edit} – SuBzer0

+0

感謝您的幫助,我解決了將@bairros = Bairro.all放在create方法中。爲什麼我需要這樣做?在Clientes控制器中,我不需要。 – SuBzer0

+0

您必須這樣做,因爲表單在第一次查看時通過「create」操作顯示,而「edit」操作顯示。如果保存失敗,表單將被重新渲染 – Iceman

相關問題