2013-02-28 50 views
0

我實現了一個使用rails 3的友誼模型..現在我想讓用戶添加新朋友...從它的外觀,我想我需要2個循環...一個循環所有用戶和另一個用於檢查該用戶是否已經是朋友......但是如果我使用2 for循環,我不會得到我期待的結果以及那些正在使用當前朋友的用戶的電子郵件用戶打印和地址打印多次(因爲第二個循環,因爲我打印它在循環內)..是否有任何其他方式來解決這個問題?設計刪除憑證

code: 
this is my view file: 

<center>Bragger's list<center><br/> 
<p> 
    <% for user in User.all %> 
    <% if current_user.email!= user.email %> 
     <% for friend in current_user.friends %> 
     <% if friend.email!=user.email %> 
      <p> 
      <%= user.email %> &nbsp; <%= link_to 'Add as Friend' , friendships_path(:friend_id => user), :method => :post %> 
      </p> 
      <br/> 
     <%end%> 
     <%end%> 
    <%end%> 
    <%end%> 

回答

0

最好的方法是過濾控制器中尚未成爲current_user的用戶列表。你可以做到這一點的

@potential_friends = User.where('id != ? AND id NOT IN (?)', current_user.id, current_user.friend_ids) 

然後,只需在這個變量循環視圖

<center>Bragger's list<center><br/> 
<p> 
    <% @potential_friends.each do |user| %> 
    <p> 
     <%= user.email %> &nbsp; <%= link_to 'Add as Friend' , friendships_path(:friend_id => user), :method => :post %> 
    </p> 
    <br/> 
    <% end %> 
</p> 
0

如何做別的事情,

User.where('user_id not in (?)', current_user.friends.map(&:id).push(current_user.id))

這將讓所有的用戶數據庫不是你的current_user的朋友,然後你只需要循環一次。