Rails 3友情模特:如何忽略好友请求?

时间:2012-03-20 17:58:47

标签: ruby-on-rails relationship destroy

我有传统的友谊模式:

用户模型具有:

has_many :friendships, :dependent => :destroy
  has_many :friends, :through => :friendships, :dependent => :destroy
  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id", :dependent => :destroy
  has_many :inverse_friends, :through => :inverse_friendships, :source => :user, :dependent => :destroy

我想仅在朋友请求已被发送并且被其他用户接受时才定义状态“朋友”。一切正常,除了我没有设法处理“忽略朋友请求”部分。

我要做的是:在用户个人资料页面上,有一个来自其他用户的请求列表,等待批准。然后用户可以接受朋友请求(然后它成为朋友)或拒绝它(然后友谊关系被破坏)。

以下是友谊控制器中阻止的代码:

<h2 class="small_v_space">Waiting your approval</h2>
<ul>
  <% for user in @user.inverse_friends %>
    <% if user.friends.exists?(@user) and not @user.friends.exists?(user) %>
      <li>
        <%=h user.name %>
          (<%= link_to "Accept", friendships_path(:friend_id => user), :method => :post %>,
           <%= link_to "Ignore", friendship_path, :controller => :friendships, :method => :delete  %>)
      </li
    <% end %>
  <% end %>
</ul>

问题是,如果我这样做,delete方法将删除最后添加的关系,而不是链接到ignore按钮的关系。

让我们使用示例这是我想破坏的关系: User_id:10 朋友:6 Friendship_id:18

我在用户的'show'页面(个人资料)上,其user_id为6.我看到用户10发出了我想忽略的好友请求。即使我设法提取正确的Friendship_id,也可以:

<%= link_to "Ignore", friendship_path(Friendship_id), :controller => :friendships, :method => :delete  %>)

导致“找不到ID为18的友谊[其中user_id = 6]”

在这种情况下,有谁知道如何在正确的关系上调用destroy动作?或者我应该采取不同的行动?

非常感谢任何线索!

修改

破坏友谊控制者的行动:

def destroy
    @friendship = current_user.friendships.find(params[:id])
    if @friendship.friend.friends.exists?(current_user)
      @friendship.destroy
      flash[:notice] = "Removed friendship."
    else
      @friendship.destroy
      flash[:notice] = "Removed friend request."
    end
    redirect_to current_user
  end

编辑2:

class Friendship
   belongs_to :user
   belongs_to: :friend, :class_name => 'User'
 end

用户A向用户B发送朋友请求(A =用户,B =该类实例中的朋友)。如果B接受请求,则创建另一个实例(B = user,A = friend)。如果存在关系A-> B和B-> A,则A是B的朋友。否则,请求保持挂起(或者可以忽略,拒绝......)。

1 个答案:

答案 0 :(得分:1)

我正在编辑我的整个答案,因为我认为我找到了问题的要点。当用户尝试与某人成为朋友时,您会向该用户添加关系,但不会将其添加到其他用户。所以,current_user.friendships.find(params[:id])期望current_user与该id有友谊,但该关系不属于他,而是属于其他用户。

我不确定我是否说得够清楚,但这是我的第二次尝试:

您的链接应该是:

<%= link_to "Ignore", friendship_path(:id => friendship_id, :friend_id => user.id), :method => :delete  %>)

然后你的行动:

def destroy
  potential_friend = User.find(params[:friend_id])
  friend_request = potential_friend.friendships.find(params[:id])

  friendship = current_user.friendships.find_by_friend_id(potential_friend.id)
  if friendship.nil?      #Users are not friends and you want to delete the friend request
    friend_request.destroy
    flash[:notice] = "Removed friend request."
  else                    #Users are friends and you want to delete the friendship
    friendship.destroy
    friend_request.destroy
    flash[:notice] = "Removed friendship."
  end
  redirect_to current_user
end

我不确定你是否应该把它变成自定义动作。正如您所看到的,它不仅仅是销毁单个对象。

相关问题