我正在嘗試創建一個Web API,允許通過電子郵件或電話號碼創建FriendShip
。Rails Web API拋出錯誤
class Api::FriendshipsController < Api::BaseController
respond_to :json
def create
friend = User.where("email = ? OR phone_number = ?", params[:emailOrPhone], params[:emailOrPhone]).first # create a friend by email or phone_number
if friend.valid? # check if the friend exists, if it does we create our new friendship
friendship = Friendship.new
friendship.user = current_user
friendship.friend = friend
if friendship.valid? # check if friendship is valid
friendship.save # if it is, we save and return a success JSON response
render json: {created: true}, status: 200
else # if it's not a valid friendship, we display a error JSON response
render json: {created: false}, status: 400
end
end
end
end
這裏是我的FriendShip
模型
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => "User"
validates_uniqueness_of :user_id, scope: :friend_id, :message => '%{friend_id} is already a friend'
validate :check_friend_and_user # prevent user trying to add him/herself as friend.
def check_friend_and_user
errors.add(:friend, "can't be the same as user") if user == friend
end
end
每當唯一性約束被侵犯,錯誤missing interpolation argument :friend_id in "%{friend_id} is already a friend" ({:model=>"Friendship", :attribute=>"User", :value=>2} given)
,錯誤代碼500
如何使它不會引發錯誤,而是繼續給出狀態代碼的'失敗json響應'400
我希望此API的調用者知道他們正在嘗試添加已經是朋友的人。取回狀態代碼500
和一堆html似乎並不能唯一標識它。所以我想以JSON的形式拋出一個錯誤並且狀態200