通过users_controller.rb中的代码修改用户的数据库

时间:2015-07-14 23:50:13

标签: ruby-on-rails ruby mongodb ruby-on-rails-4

我有两个用户,我们称之为UserA和UserB。 UserA向UserB发送好友请求。这导致创建一个名为“Friendtokens'”的新属性。在UserB的数据库中。使用的数据库是MongoDB。

Friendtokens: {"919839398393"=>{"atoken"=>"f704e803061e594150b09ad8acabfc6105ac85ab", "confirmed"=>true}}

现在,当UserA决定删除UserB时,我需要修改UserB的DB的Friendtokens并删除UserA的手机号码。从它。

如何通过在users_controller.rb中编写一个简单的代码来实现这一目标的任何指导都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

您提供的信息很少。这是我建议的模型化:

class User
  include Mongoid::Document
  embeds_many :friend_tokens
  field :phone_number

class FriendToken
  include Mongoid::Document
  embedded_in :user
  belongs_to :friend, class_name: "User"
  field :confirmed, type: Boolean

  def phone_number
    confirmed ? friend.phone_number : "Friend not confirmed, not showing user phone number !"
  end

users_controller.rb

def create_friend_request
  @user.friend_tokens << FriendToken.create(friend_request_params)
end

def confirm_friend_request
  token = @userA.friend_tokens.select{|t| t.friend == @userB}.first
  if token
    token.confirmed = true
    token.save
  else
    # Error message
  end
end

def delete_friend
  friend_for_A = @userA.friend_tokens.select{|t| t.friend == @userB}.first
  # Check it has been found
  if friend_for_A
    # Delete friend token for A
    friend_for_A.delete
    # Switch to unconfirmed for user B (we can also assume the token exists)
    friend_for_B = @userB.friend_tokens.select{|t| t.friend == @UserA}.first
    friend_for_B.confirmed = false
    friend_for_B.save
  else
    # Error messages
  end
end