2013-01-06 117 views
1

V3.2.1驗證唯一性範圍不工作

不知道爲什麼「計數」快到了零和索引將不會呈現,如「計數」它一直在細每一個模型,直到我做的唯一性與範圍驗證。

有什麼建議嗎?


MODEL

Class FeatureIcon < ActiveRecord::Base 
    belongs_to :user 

    validates_presence_of :img_size, :feature_name, :image, :user_id 
    validates_uniqueness_of :img_size, :scope => :feature_name 

    //paperclip interpolates stuff.... 
end 

CONTROLLER

before_filter :load_user 

def index 
    @feature_icons = @user.feature_icons.all 
    @feature_icon = @user.feature_icons.new 

    respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @feature_icons } 
    format.js 
    end 
end 


def create 
    @feature_icon = @user.feature_icons.new(params[:feature_icon]) 

    respond_to do |format| 
    if @feature_icon.save 
     format.html { redirect_to user_feature_icons_url, notice: 'successfully created.' } 
     format.json { render json: @feature_icon, status: :created, location: @feature_icon } 
     format.js 
    else 
     format.html { render action: "index" } 
     format.json { render json: @feature_icon.errors, status: :unprocessable_entity } 
    end 
    end 
end 

ERROR

NoMethodError in Feature_icons#create 

undefined method `count' for nil:NilClass 
    Extracted source (around line #7): 

    6:  <div class="count"> 
    7:   <div id="count" class="feed-count"><%= @feature_icons.count %></div> 
    8:  </div> 

回答

2

create方法中,您使用的是實例@feature_icons(帶's'),但在視圖中您使用的是@feature_icon(不帶's'),所以@feature_iconsnil

如果保存失敗,則行format.html { render action: "index" }會呈現視圖index.htm.erb,但控制器中的方法index未被調用。試着用

if @feature_icon.save 
    #... nothing to change 
else 
    format.html do 
    @feature_icons = @user.feature_icons.all 
    render action: "index" 
    end 
    format.json { render json: @feature_icon.errors, status: :unprocessable_entity } 
end 

if @feature_icon.save 
    #... nothing to change 
else 
    format.html { redirect_to :index } 
    format.json { render json: @feature_icon.errors, status: :unprocessable_entity } 
end 
+0

首先建議的工作!謝謝Baldrick! – econduck