Rails - 未定义的方法`each'为0:Fixnum

时间:2012-07-14 16:25:25

标签: ruby-on-rails ruby-on-rails-3

我在Ruby on Rails undefined method 'each' for 0:Fixnum中收到以下错误。

以下是应用程序跟踪:

app/controllers/videos_controller.rb:23:in `new'
app/controllers/videos_controller.rb:23:in `create'

我的控制器创建了新动作:

  def new
    @video = Video.new
  end

  def create
    method = 'get_' + params[:video][:provider] + '_video_id'
    params[:video][:provider_video_id] = Video.send(method, params[:video][:url])
    params[:video][:thumb] = Video.get_thumb_from_youtube(params[:video][:provider_video_id])
    params[:video][:views] = params[:video][:likes] = 0    
    params[:video][:user_id] = current_user
    @video = Video.new(params[:video])
    if @video.save
      redirect_to video_path(@video), notice:'Video added successfully.'
    else
      render :new
    end
  end

这是我的view.html.haml:

= form_for @video do |f|
 - if @video.errors.any?
  .error_explanation
    %h2= pluralize(@video.errors.count, "error")
    prohibited this user from being saved:

    %ul
      - @video.errors.full_messages.each do |msg|
        %li= msg
.field
  = f.label :title
  = f.text_field :title
.field
  = f.label :description
  = f.text_area :description
%br
.field
  = f.label :url, 'URL'
  = f.text_field :url
%br
.field
  Provider
  = radio_button :video, :provider, 'vimeo'
  = f.label :provider, 'Vimeo', :value => 'vimeo'
  = radio_button :video, :provider, 'youtube' 
  = f.label :provider, 'Youtube', :value => 'youtube'
%br
.field
  Category
  = collection_select(:video, :category_id, Category.all, :id, :name, :include_blank => true)
%br
.actions
  = f.submit "Add video"   

1 个答案:

答案 0 :(得分:2)

params[:video][:views] = params[:video][:likes] = 0

params[:video][:views] = 0

我认为video.likes是一个关联,而不是一个计数,因此它需要一个Enumerable。如果它是关联,则rails会尝试将您添加到likes的元素分配给video模型。添加它们的第一步是使用each进行迭代。这就是错误的来源。