2017-02-10 7 views
0

FriendShipをemailまたはphone_numberで作成できるWeb APIを作成しようとしています。ここで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

答えて

1

友人が友人クラスを介して既にユーザに関連付けられているかどうかを判断することです。 Userオブジェクトのhas_many:friendships関連付けで簡単にすることができます。

また、電子メールまたは電話で検索する方法は、不必要にあいまいであり、他の目的のために一方または他方を別々にトラッキングする場合は問題があります。別々のデータベース列に分けられているので、あなたがしたいと思っているようです。私はあなたがちょうど2つのフォーム入力電子メールまたは電話番号を入れて、コントローラに1つだけ通すことができると思います。あなたが1つだけ持っていなければならない場合は、フォームがJavascriptなどで何を提出するかを決めることができます。

この場合、フォームの初期データとともに識別子のタイプを送信する方が良いので、どちらか一方を探すことができます。したがって、フォームは明示的に列参照識別子を送信します。 paramsが、その後、あなたは、このコード

# assuming you're passing via a params hash that would look like  
# one or the other of the following 
# {friendship: {email: "[email protected]"}} 
# {friendship: {phone_number: "123-123-1234"}} 
def create 
    if current_user.friendships.find_or_create_by(friendship_params) 
    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 

protected 


def friendship_params 
    require(:friendship).permit(:email, :phone_number) 
end 
にしようとして何を行う可能性のparamsでそれとルビーのハッシュ

{friendship: {email: "[email protected]"}}

に相当します

関連する問題