私は、モバイルアプリケーション用のRailsバックエンドAPIを作成しており、受け入れられたステータスコードで一意のレコードを検証したいと考えています。ステータスが受け付けられた一意の検証を処理する
@Why?
モバイルアプリからのエントリを保存するときに、重複したレコードをRailsに保存しないようにしたいが、エラーステータスではなくRailsからモバイルアプリに「受け入れられたステータスコード」を送信して、 。私が好きな
モデル
class Entry < ActiveRecord::Base
validates :uuid, uniqueness: true
end
コントローラ
def create
# Check if the same record already exists
entry = Entry.find_by(uuid: entry_params[:uuid])
if entry.present?
render json: {errors: {message: 'The same uuid already exists.'}}, status: :accepted
return
end
entry = Entry.new
entry.attributes = entry_params
if entry.save
render json: entry, status: :created
else
render json: entry.errors, status: :unprocessable_entity
end
end
上記のコードは動作しますが、私はきちんと代わりにレールの検証を使用することができる場合、私は疑問に思って。
これは私が試みたものですが、残念なことにユニークなuuidエラーを取得できませんでした。この状況に対処するためのよりよい方法はありますか?
ApplicationControllerに
rescue_from ActiveRecord::RecordNotUnique, with: :record_not_unique
def record_not_unique
render json: {errors: {message: 'Record not unique.'}}, status: :accepted
end
は非常に明確を提供いただき、ありがとうございます見る! –