ネストされた属性を受け入れるドット表記ではなく完全なハッシュを使用した API での Ruby on Rails モデル エラー
概要
そこで、Rails 7をAPIモードで実行しており、ドット表記文字列を含むエラーではなく完全なオブジェクトとしてエラーを返したいと考えています。 Address がphone_number のネストされた属性を受け入れるとします。
私のコードは次のとおりです。
def create
@address = Address.new(address_params)
if @address.save
render json: @address, status: :created
else
render json: {errors: @address.errors}, status: :unprocessable_entity
end
end
無効な電話番号の場合は返されます
{
"errors": {
"phone_number.number": "is not a valid number"
}
}
返してもらう最善の方法は何ですか
{
"errors": {
"phone_number": {
"number": "is not a valid number"
}
}
}
これらをクライアント側で解析することもできますが、これはサーバーで処理する方が適しているようです。
ありがとう
解決策
これが私が入手した中で最も近いものです。私はこのソリューションのファンではありません。これを行うために渡すことができるオプションがあるべきだと思うからです。
# Convert a hash that may have flat keys with dots into a nested hash.
# This is useful because nested attributes return as dot notation and that creates
# redundant code on the client that would have to handle this.
# @param hash [Hash] the hash to convert.
# @return [Hash] the nested hash.
def flat_keys_to_nested(hash)
hash.each_with_object({}) do |(key, value), all|
key_parts = key.to_s.split('.').map!(&:to_sym)
leaf = key_parts[0...-1].inject(all) { |h, k| h[k] ||= {} }
leaf[key_parts.last] = value
end
end
def create
@address = Address.new(address_params)
if @address.save
render json: @address, status: :created
else
render json: {errors: flat_keys_to_nested(@address.errors.to_hash)}, status: :unprocessable_entity
end
end
これはエラーをハッシュにダンプし、ドット表記を取得して完全なハッシュにするインターネット上の未知のコードを使用します。