Reputation: 2292
I get this error message:
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'
Model:
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
Controller:
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!
The AvatarUploader was generated and the avatar:string column was added to the users table through the migration execution. I am not sure what's wrong with it.
Extra info: I use Rails: 4.2.4, Ruby: 2.2.1
Many thanks !
Upvotes: 0
Views: 264
Reputation: 4147
The error is pretty informative. When you call User.where(email: params[:user][:email])
you don't get a User
object, you get an ActiveRecord_Relation
object, wich can contain multiple ActiveRecord
objects or be empty. To get a single User
you want to use find_by
instead of where
, then you'll be able to get access to the avatar.
Upvotes: 2