【问题标题】:Rails User add friend through HTTP requestRails 用户通过 HTTP 请求添加好友
【发布时间】:2016-11-21 11:09:43
【问题描述】:

所以我的 Rails 应用程序中有一个User 模型(不是吗?:D)。用户可以添加朋友。

我正在关注这里给出的答案:Model design: Users have friends which are users

用户.rb

class User < ApplicationRecord
  ...
  has_and_belongs_to_many :friends,
    class_name: "User",
    join_table: :friends_users,
    foreign_key: :user_id,
    association_foreign_key: :friend_id

  ...
end

我使用以下方法生成了我的迁移文件:

rails generate CreateFriendshipJoinTable users friends

经过一些修改的生成迁移文件:

迁移文件

class CreateFriendshipsJoinTable < ActiveRecord::Migration[5.0]
  def change
    create_join_table :users, :friends do |t|
      t.index [:user_id, :friend_id]
      t.index [:friend_id, :user_id]
    end
  end
end

更新操作

def update
    user = User.find_by({id: params[:id]})

    skip_authorization and render status: :not_found and return unless user

    authorize user

    attributes = policy(User).permitted_attributes_for_update

    if user.update_attributes!(params.permit(attributes))
        render json: user
    else
        render status: :unprocessable_entity
    end
end

测试

  test "user friends - should successfully add a friend" do
    put user_path(@jim), params: {user_id: @sarah.id}, headers: user_authenticated_header(@jim)
    assert_response :success

    json = JSON.parse(response.body)
    puts "json = #{json}"

    user = User.find_by({id: @jim.id})
    assert_includes user.friends, @sarah
  end

我的测试失败了。

我不确定 HTTP PUT 请求的参数是告诉我的用户“朋友”id 是某个数字,我的用户更新操作应该使用给定的朋友 id 找到其他用户并将该用户添加为第一个用户。

但是,我可以通过创建两个用户成功地使用rails console --sandbox 添加朋友,然后使用以下代码:

jim.friends << sarah

这正如预期的那样将莎拉添加为吉姆的朋友,这让我相信我的餐桌关系是......一半......工作?

有什么想法吗? :D

【问题讨论】:

    标签: ruby-on-rails associations foreign-key-relationship


    【解决方案1】:

    我决定使用不同的方法并创建了一个名为“add_friend”的新操作:

    def add_friend
      friend = User.find_by({id: params[:id]})
    
      skip_authorization and render status: :not_found and return unless friend
    
      authorize friend
    
      current_user.friends << friend
      friend.friends << current_user
    
      if current_user.save! && friend.save!
        render json: current_user, status: :ok
      else
        render status: :bad_request
      end
    end
    

    我的测试现在通过了,我的用户 Jim 有一个朋友 Sarah :D

    不过,我稍后需要重构此逻辑,以在实际连接之前包含朋友邀请/请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      相关资源
      最近更新 更多