Rails4 アプリの ajax 呼び出しの 1 つで json を返す json ビューを作成しました。ここで提案されたアイデアを使用しました https://stackoverflow.com/a/12832116/1560470
しかし、他のステータス コードを適用しても、ステータス コードは常に 200 のままです。
view/managers/create.json.jbuilder の jbuilder ビューは次のようになります。
if @manager.errors.messages.any?
envelope(json, :unprocessable_entity, @manager.errors.messages) do
json.success false
end
else
envelope(json, :created) do
json.success true
end
end
私のアプリケーションヘルパーは次のように動作します:
module ApplicationHelper
def envelope json, status, errors
json.status status
json.data do
yield if block_given?
end
json.errors errors
end
end
私のコントローラーは次のとおりです。
def create
@manager = Manager.new manager_params
@saved = ( @manager.valid? && @manager.save )
end
status
jbuilder ビューのように params 値を渡していることも:unprocessable_entity
わかりますが、応答は毎回 200 として返されます。どのステータス コードを使用しても、常に 200 が返されます。ステータス コードはhttp://guides.rubyonrails.org/layouts_and_rendering.htmlで定義されています。