RoR 应用程序中来自 Carrierwave 的未定义头像方法

Undefined avatar method from Carrierwave in RoR application

我收到此错误消息:

Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.0ms)

NoMethodError (undefined method `avatar=' for #<User::ActiveRecord_Relation:0x007f87e4c304d8>):
  app/controllers/api/v1/user_controller.rb:10:in `upload'

型号:

class User < ActiveRecord::Base
  acts_as_token_authenticatable

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  mount_uploader :avatar, AvatarUploader

  validates_presence_of   :avatar
  validates_integrity_of  :avatar
  validates_processing_of :avatar
end

控制器:

module Api
  module V1
    class UserController < ApplicationController
      before_action :set_user, only: [:show, :update, :destroy]
      #before_filter :authenticate_user_from_token!

      def upload
        puts "here => " + params[:user][:email].to_s
        @user = User.where(email: params[:user][:email])
        @user.avatar = params[:user][:file]
        @user.save!
        p @user.avatar.url # => '/url/to/file.png'
        p @user.avatar.current_path # => 'path/to/file.png'
        p @user.avatar_identifier # => 'file.png'
      end
...

environment.rb:

# Load the Rails application.
require File.expand_path('../application', __FILE__)

require 'carrierwave/orm/activerecord'

# Initialize the Rails application.
Rails.application.initialize!

已生成 AvatarUploader,并通过迁移执行将 avatar:string 列添加到用户 table。我不确定它有什么问题。

额外信息:我使用 Rails:4.2.4,Ruby:2.2.1

非常感谢!

错误信息非常丰富。当你调用 User.where(email: params[:user][:email]) 时,你不会得到 User 对象,你会得到一个 ActiveRecord_Relation 对象,它可以包含多个 ActiveRecord 对象或为空。要获得单个 User 您想使用 find_by 而不是 where,那么您将能够访问头像。