我收到此错误消息:
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列添加到users表中。我不确定它有什么问题。
额外信息:我使用Rails:4.2.4,Ruby:2.2.1
非常感谢!
答案 0 :(得分:2)
该错误非常有用。当您致电User.where(email: params[:user][:email])
时,您无法获得User
个对象,您将获得一个ActiveRecord_Relation
个对象,该对象可能包含多个ActiveRecord
个对象或为空。要获得一个User
您要使用find_by
而不是where
,您就可以访问该虚拟角色。