2011-12-20 143 views
0

我試圖將驗證合併到我的一些模型中,但是當這樣做時,如果某些內容沒有驗證,我會收到錯誤消息「您沒有對象,當您沒有期待它!「,」你可能期望一個Array的實例。「和「評估nil.map時發生錯誤」。看看my code,我在第3行後面加上「validates_uniqueness_of:name」和「validates_format_of:name,:with =>/^ [A-Za-z \ d _] + $ /」,並且每當我一個不會驗證的提交,我得到的錯誤。新對象驗證後的無對象

應用跟蹤:

app/views/subreddits/new.html.haml:13:in `block in _app_views_subreddits_new_html_haml___455774545377436650_34289940' 
app/views/subreddits/new.html.haml:4:in `_app_views_subreddits_new_html_haml___455774545377436650_34289940' 
    app/controllers/subreddits_controller.rb:53:in `block (2 levels) in create' 
    app/controllers/subreddits_controller.rb:48:in `create 

'

+1

似乎問題出在這個視角。你有什麼第13行?我猜錯誤信息循環? – apneadiving

+0

@apneadiving - https://github.com/Chiggins/RedditClone/blob/master/app/views/subreddits/new.html.haml ...第13行包含:= select(「subreddit」,「link_type」,@ link_types) – Chiggins

+1

好,所以'@ link_types'爲零。你如何設置它? – apneadiving

回答

3

基本上,在控制器的create動作,你需要設置@link_types所以,當你無法保存,就可以正確地呈現new模板。您可能應該將@link_types值設置爲常量,或者在幫助程序中將其設置爲DRYer。

def create 
    params[:subreddit][:created_by_id] = session[:user_id] 
    @subreddit = Subreddit.new(params[:subreddit]) 

    respond_to do |format| 
    if @subreddit.save 
     format.html { redirect_to @subreddit, notice: 'Subreddit was successfully created.' } 
     format.json { render json: @subreddit, status: :created, location: @subreddit } 
    else 
     format.html do 
     @link_types = {"link" => "link", "text" => "text", "both" => "both"} 
     render action: "new" 
     end 
     format.json { render json: @subreddit.errors, status: :unprocessable_entity } 
    end 
    end 
end 
+0

好的,我明白你在說什麼了。雖然,「DRYer」是什麼意思? – Chiggins

+0

@Chiggins DRY是不要重複自己的首字母縮略詞。查看維基百科文章:http://en.wikipedia.org/wiki/Don%27t_repeat_yourself。 – htanata

+0

啊我得了,謝謝! – Chiggins