1

v3.2.1

不知道为什么“计数”出现为零并且索引不会呈现,因为“计数”在每个模型中都很好,直到我通过范围验证进行唯一性。

有什么建议么?


模型

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

控制器

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>
4

1 回答 1

2

在该create方法中,您实例化@feature_icons(使用“s”),但在您使用的视图中@feature_icon(没有“s” )@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

或者

if @feature_icon.save
  #... nothing to change
else
  format.html { redirect_to :index }
  format.json { render json: @feature_icon.errors, status: :unprocessable_entity }
end
于 2013-01-06T10:53:36.450 回答