Ruby on Rails Carrierwave:ActiveRecord :: RecordInvalid(验证失败:头像不能为空):

时间:2016-04-09 16:48:49

标签: ruby-on-rails api carrierwave rest-client

我正在尝试将Carrierwave与RoR API集成,我遇到了以下错误消息:

ActiveRecord::RecordInvalid (Validation failed: Avatar can't be blank):
  app/controllers/api/v1/user_controller.rb:10:in `upload'

用户控制器:

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

      def upload        
        @user = User.find_by(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
...

输出:

params[:user][:email] => user@email.com
params[:user][:file] => #<File:0x007fbacc083318>

使用rest-client gem执行API调用:

...
response = RestClient.post 'http://' + @host.to_s + ':' + @port.to_s + '/api/user/upload', {'user' => { 'email' => email, 'file' => File.new("/Users/admin/Desktop/me.jpg", 'rb')}}.to_json, :content_type => :json
...

我觉得帖子不正确。

非常感谢!

1 个答案:

答案 0 :(得分:0)

试试这个,我不太确定。让我知道!

  def upload        
    @user = User.find_by(email: params[:user][:email])

    File.open(params[:user][:file]) do |f|
       @user.avatar = f
    end

    @user.save!
  end