V3.2.1
不确定为什么'count'即将出现nil并且index将无法呈现,因为'count'在每个模型中都很好,直到我使用范围验证进行唯一性。
有什么建议吗?
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
错误
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>
答案 0 :(得分:2)
在create
方法中,您实时@feature_icons
(带有's'),但在视图中您使用的是@feature_icon
(没有's'),所以{ {1}}是@feature_icons
。
如果保存失败,则行nil
会呈现视图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