我正在开发一个在后端使用Ruby on Rails的android应用程序。我使用Rails创建了REST API
。我需要上传图像以及其他数据。基本上,我有"user"
和"Event"
对象。每个用户可以创建许多事件。用户可以将图像与事件描述一起附加。我将Postgres DB用于文本数据存储,并且工作正常。但是问题是当我将云API "Cloudinary"
用于images
时。我不知道是什么问题。我收到以下错误:
{
"status": 500,
"error": "Internal Server Error",
"exception": "#<NoMethodError: undefined method `upload' for nil:NilClass>",
"traces": {
"Application Trace": [
{
"exception_object_id": 78590280,
"id": 26,
"trace": "app/controllers/events_controller.rb:23:in `create'"
}
],
"Framework Trace": [
{
"exception_object_id": 78590280,
"id": 0,
"trace": "activestorage (6.0.1) app/models/active_storage/blob.rb:194:in `upload_without_unfurling'"
},
{
"exception_object_id": 78590280,
"id": 1,
"trace": "activestorage (6.0.1) lib/active_storage/attached/changes/create_one.rb:25:in `upload'"
},.....
当我从Postman测试API时,我已经完成了以下步骤:
我在Gemfile
中添加了以下宝石:
gem 'cloudinary', require: false
gem 'activestorage-cloudinary-service'
然后我跑:
bundle
rails active_storage:install
rails db:migrate
我在config/storage.yml
中添加了以下内容:
cloudinary:
service: Cloudinary
cloud_name: <%= ENV['CLOUDINARY_CLOUD_NAME'] %>
api_key: <%= ENV['CLOUDINARY_API_KEY'] %>
api_secret: <%= ENV['CLOUDINARY_API_SECRET'] %>
然后我在config/environments/**
文件中添加了以下行:
config.active_storage.service = :cloudinary
Routes.rb如下所示:
Rails.application.routes.draw do
resources :events do
get :event_image, on: :member
end
resources :users
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
EventsController
如下:
class EventsController < ApplicationController
before_action :set_event, only: [:show, :update, :destroy]
# GET /events
def index
@events = Event.all.with_attached_event_image
render json: @events.map {|event|
event.as_json.merge({event_image: url_for(event.event_image)})}
end
# GET /events/1
def show
event = Event.find(params[:id])
render json: event.attributes.merge(event_image: url_for(event.event_image))
end
# POST /events
def create
@event = Event.new(event_params)
# Cloudinary::Uploader.upload(@event.event_image)
if @event.save
render json: @event, status: :created, location: @event
else
render json: @event.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /events/1
def update
if @event.update(event_params)
render json: @event
else
render json: @event.errors, status: :unprocessable_entity
end
end
# DELETE /events/1
def destroy
@event.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_event
@event = Event.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def event_params
params.require(:event).permit(:title, :description, :country, :city, :event_location, :event_date, :event_time, :event_status, :user_id, :event_image)
end
end
请记住:该API在使用本地存储时效果很好!错误是当我将存储服务切换到:cloudinary
时发生的。有人可以帮忙吗?