2014-04-22 11 views
0

我用回形針製作一個圖片庫,並保持創建新照片時收到此錯誤未定義的方法`照片的零:NilClass

undefined method `pictures' for nil:NilClass 

。我有我所有的協會的成立,並喜歡

畫廊 - >的has_many:圖片
圖片 - > belongs_to的:像冊

,並在我的pictures.controller

def create 
    @picture = @gallery.pictures.new(picture_params) 
    respond_to do |format| 
    if @picture.save 
    format.html { redirect_to @picture, notice: 'Picture was successfully created.' } 
    format.json { render :show, status: :created, location: @picture } 
    else 
    format.html { render :new } 
    format.json { render json: @picture.errors, status: :unprocessable_entity } 
    end 
end 

我我花了最後一天的時間試圖弄清楚這一點。

+0

「@ gallery」在哪裏定義或設置? – lurker

+0

@lurker它沒有設置。我想這就是爲什麼它不起作用。如何設置圖庫以便圖片屬於gallery_id? – equaltwelve

+0

你試過用'Picture.new(params)'替換'@ gallery.pictures.new(picture_params)'嗎? –

回答

2

我們可以根據發佈的內容真正告訴你的是@gallery爲零。你實際上必須分配一些東西到@gallery,Rails不包含樣板代碼來爲你填充該變量。

+0

是的,我想通了。那麼,我應該如何設置@ gallery來將圖片分配給圖庫ID? – equaltwelve

+0

就像你會使用其他任何模型一樣; '@gallery = Gallery.find(gallery_id_goes_here)' – meagar

+0

我試過了,它仍然會拋出同樣的錯誤?很奇怪。 – equaltwelve

相關問題