2016-04-09 15 views
0

我收到此错误信息:未定义的化身方法

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,红宝石:2.2.1

非常感谢!

回答

1

错误信息丰富。当您拨打User.where(email: params[:user][:email])时,您不会收到User对象,您会收到一个ActiveRecord_Relation对象,其中可能包含多个ActiveRecord对象或为空。要获得单个User,您希望使用find_by而不是where,那么您将可以访问该头像。

+0

感谢您分享此信息,以解决此问题。 –