新对象验证后的Nil对象

时间:2011-12-20 20:30:35

标签: ruby-on-rails ruby validation

我正在尝试将验证合并到我的一些模型中,但是当这样做时,如果某些内容无法验证,我会收到错误消息“当你没想到它时,你有一个零对象!”,“您可能期望有一个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 个答案:

答案 0 :(得分: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
相关问题