我正在尝试创建一个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