実現したいこと
Ruby on Railsで画像を受け取って、それのURLを返すAPIの実装です。
発生している問題・分からないこと
添付コードのupdateアクションで、なぜか、一つ前の画像のURLが返ってきます。
該当のソースコード
Ruby
1require 'tempfile'2require 'httparty'3 4class FormulasController < ApplicationController5 before_action :set_project6 before_action :set_formula, only: [:update, :destroy]7 8 # GET projects/:project_id/formulas9 def index10 @formulas = @project.formulas 11 render json: @formulas12 end13 14 # POST projects/:project_id/formulas15 def create16 @formula = @project.formulas.new(formula_params)17 if @formula.save 18 render json: @formula, status: :created, location: project_formula_url(@project, @formula)19 else20 render json: @formula.errors, status: :unprocessable_entity21 end22 end23 24 # PATCH /projects/:project_id/formulas/:id25 def update26 tmp_img = get_img 27 if tmp_img 28 @formula.image.attach(io: tmp_img, filename: 'image.png', content_type: 'image/png')29 # @formula.image.analyze30 @formula.save 31 end32 if @formula.update(formula_params)33 @formula.reload 34 Rails.cache.clear 35 # image_url = rails_blob_url(@formula.image) if @formula.image.attached?36 image_url = url_for(@formula.image) if @formula.image.attached?37 render json: { formula: @formula, image_url: image_url }38 else39 render json: @formula.errors, status: :unprocessable_entity40 end41 end42 43 # DELETE /projects/:project_id/formulas/:id44 def destroy45 @formula.destroy 46 end47 48 private49 def set_project50 @project = Project.find(params[:project_id])51 end52 53 def set_formula54 @formula = @project.formulas.find(params[:id])55 end56 57 def formula_params58 params.require(:formula).permit(:file_name, :content)59 end60 61 def get_img62 if ENV['RAILS_ENV'] == 'development'63 url = Rails.application.credentials.tex_compile[:dev_url] + '/latex_to_image'64 else65 url = Rails.application.credentials.tex_compile[:prod_url] + '/latex_to_image'66 end67 body = {68 "formula": @formula.content.gsub('\\', '\\\\')69 }70 response = HTTParty.post(url, 71 body: body.to_json,72 headers: { 'Content-Type' => 'application/json' }73 )74 if response.success?75 temp_img = Tempfile.new(['image', '.png'])76 temp_img.binmode 77 temp_img.write(response.body)78 temp_img.rewind 79 temp_img 80 else81 puts 'Failed to get image from API'82 nil83 end84 end85 end86
試したこと・調べたこと
上記の詳細・結果
Railsのキャッシュの削除や、@formula.reloadなどを試したが変化なし
ChatGPTに繰り返し聞いたが無理でした
補足
rails 7です

0 コメント