我的方法中的条件非常复杂,因此我想使其简化并易于阅读。
def check
@friends = params[:friends]
@key = User.find_by_email @friends[0]
@val = User.find_by_email @friends[1]
user1 = User.where(email: @friends[0])
user2 = User.where(email: @friends[1])
if Friendship.where(user: @key, friend: @val).exists?
render json: {message: "Relationship already establish"}
else
if user1.exists? && !user2.exists?
@user = @key
@friend = User.create email: @friends[1]
@user.friendships.create friend_id: @friend.id
render json: {success: true}
elsif !user1.exists? && user2.exists?
@friend = @val
@user = User.create email: @friends[0]
@user.friendships.create friend_id: @friend.id
render json: {success: true}
elsif user1.exists? && user2.exists?
if Friendship.where(user: @key, friend: @val).exists?
render json: {message: "Relationship already establish"}
else
@user = @key
@friend = @val
@user.friendships.create friend_id: @friend.id
render json: {success: true}
end
else
@user = User.create email: @friends[0]
@friend = User.create email: @friends[1]
@user.friendships.create friend_id: @friend.id
render json: {success: true}
end
end
end
还有什么其他方法可以简化此方法,但仍然可以给我正确的结果
答案 0 :(得分:5)
def check
@user = User.find_or_create_by(email: params[:friends][0])
@friend = User.find_or_create_by(email: params[:friends][1])
if Friendship.where(user: @user, friend: @friend).exists?
render json: {message: "Relationship already establish"}
else
@user.friendships.create(friend_id: @friend.id)
render json: {success: true}
end
end