2017-05-26 9 views
-2

同じエラーで多くの質問がありますが、私の問題を解決するものは見つかりませんでした。だから、私は "Bairro"を持っていて、そこに "Clientes"と "Imoveis"が属しています。問題は、顧客「Cliente」を作成するだけで正常に動作していることですが、私は「Imovel」を作成するために行くとき、私はエラーがあります:nilのための
未定義のメソッド `マップを」:NilClassとのハイライト:Rails:未定義メソッド `map 'for nil:NilClass

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

Imovel.rbは次のようである:@bairros = Bairro.allデないときに通常、このエラーが発生

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 

:私はこれを持っているコントローラで

class Imovel < ApplicationRecord 
    belongs_to :bairro 
    belongs_to :cliente 
end 

この場合は罰金は科されません。

ビューはうまく開いて編集できますが、保存するとエラーが発生します。 どうすればこの問題を解決できますか?

答えて

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行うrespond_to = Bairro.all を @bairrosを更新|形式で| if @ imovel.update(imovel_params) format.html {redirect_to @imovel} else format.html {render:edit} – SuBzer0

+0

助けてくれてありがとう、私は@bairros = Bairro.allを作成メソッドに入れました。なぜ私はそれを置く必要がありますか? Clientesのコントローラーでは、私はそうする必要はありませんでした。 – SuBzer0

+0

フォームは送信時に 'create'アクションで表示されるので、最初に表示されたときは' edit'アクションが表示されるためです。保存に失敗した場合は、フォームが再レンダリングされます – Iceman

関連する問題