2016-04-09 18 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

感謝您分享此信息,以解決此問題。 –