【发布时间】:2012-03-29 22:36:33
【问题描述】:
如果
我想隐藏我的“添加朋友”链接
- current_user 和@user 是朋友
- 有一个待处理的好友请求
- current_user 和@user 有相同的id(相同的用户)
如果 current_user 和 @user 是朋友,则“添加朋友”链接不会显示。问题是当有待处理的好友请求时。提交好友请求后,我仍然会看到“添加好友”链接。
我认为的条件有问题吗?
当我在控制台中运行这两个条件时:
current_user.pending_friends.include?(@user) 和 @user.pending_friends.include?(current_user),即使我的数据库显示有待处理的请求,我也得到了错误。
这是我的看法:
用户/show.html.erb
<% if signed_in? %>
<% if @user == current_user || current_user.friends.include?(@user)
|| current_user.pending_friends.include?(@user)
|| @user.pending_friends.include?(current_user) %>
<% else %>
<%= link_to friendships_path(:user_id => current_user.id,
:friend_id => @user.id), :method => :post, :action => 'create' do %>
Add Friend
<% end %>
<% end %>
<% end %>
用户模型
has_many :friendships
has_many :inverse_friendships,
:class_name => "Friendship",
:foreign_key => "friend_id"
has_many :direct_friends,
:through => :friendships,
:conditions => "status = 'accepted'",
:source => :friend
has_many :inverse_friends,
:through => :inverse_friendships,
:conditions => "status = 'accepted'",
:source => :user
has_many :pending_friends,
:through => :friendships,
:conditions => "status = 'pending'",
:foreign_key => "user_id",
:source => :user #this line is incorrect. see correction below.
has_many :requested_friends,
:through => :friendships,
:source => :friend,
:conditions => "status = 'requested'"
def friends
direct_friends | inverse_friends
end
这是我的友谊控制器的创建操作,所以你们可以看到关系是如何在数据库中创建的:
def create
@user = User.find(current_user)
@friend = User.find(params[:friend_id])
params[:friendship1] = {:user_id => @user.id, :friend_id => @friend.id, :status => 'pending'}
params[:friendship2] = {:user_id => @friend.id, :friend_id =>@user.id, :status => 'requested'}
@friendship1 = Friendship.create(params[:friendship1])
@friendship2 = Friendship.create(params[:friendship2])
if @friendship1.save && @friendship2.save
flash[:success] = "Friend request submitted."
redirect_to @friend
else
flash[:error] = "Friend request failed."
redirect_to @friend
end
end
感谢收看!
编辑:发现我的错误并在下面发布答案。
:pending_friends 的来源应该是:friend,而不是:user。以下更正。
has_many :pending_friends,
:through => :friendships,
:conditions => "status = 'pending'",
:foreign_key => "user_id",
:source => :friend
【问题讨论】:
-
你有创建这样一个系统的参考吗?
标签: ruby-on-rails ruby-on-rails-3