Я пытаюсь скрыть ссылку "Добавить друга", если
- current_user и @user - друзья
- есть ожидающий запрос на добавление в друзья
- current_user и @user имеют одинаковый идентификатор (один и тот же пользователь)
Ссылка «Добавить друга» не отображается, если current_user и @user являются друзьями. Проблема в том, что есть ожидающий запрос на добавление в друзья. Я все еще вижу ссылку "Добавить друга" после того, как отправляю запрос на добавление в друзья.
Что-то не так с условиями на мой взгляд?
Когда я запускаю эти два условия в моей консоли:
current_user.pending_friends.include?(@user)
и @user.pending_friends.include?(current_user)
, я получаю false, хотя в моей базе данных отображается ожидающий запрос.
Вот мой взгляд:
Пользователи / 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
Вот действие create из моего контроллера дружбы, чтобы вы, ребята, могли видеть, как создаются отношения в БД:
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 должен быть: друг, а не: пользователь. Исправление ниже.
has_many :pending_friends,
:through => :friendships,
:conditions => "status = 'pending'",
:foreign_key => "user_id",
:source => :friend