Просмотр не скрывающей ссылки «Добавить друга» во время ожидающего запроса друга (модель дружеских отношений) - PullRequest
0 голосов
/ 30 марта 2012

Я пытаюсь скрыть ссылку "Добавить друга", если
- 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

1 Ответ

1 голос
/ 30 марта 2012

Я предлагаю вам добавить модульные тесты для этих ассоциаций, так как они выглядят сложными и не простыми для понимания.

  1. добавить светильники:

    # test/fixtures/users.yml
    current_user: 
      id: 1
      name: Current User
    another_user:
      id: 2 
      name: Your friend
    
    # test/fixtures/friendships.yml
    pending_friend:
      id: 1
      status: pending
      user_id: 1 # 
      # other attributes
    requested_friend:
      id: 2
      status: requested
      user_id: 2 # 
      # other attributes
    
  2. написать код модульного теста, чтобы сказать себе, что ассоциации верны:

    # test/model/user_test.rb
    class UserTest <  # extend Rails unit test class
      def test_the_requested_friendship 
        assert users(:current_user).requested_friends.include?( users(:another_user))
      end
      def test_the_pending_friendships
        # your assertion here
      end
    end
    

ВНИМАНИЕ: приведенный выше код - просто идея, я еще не проверял их. Вы должны реализовать свой код самостоятельно.

и я предлагаю вам использовать «rspec», поскольку он более выразителен, чем классический тестовый модуль.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...