0

I am trying to finish my forum application. I want arrange user Friendships. I am using devise as authentication system. I want some suggestions. Shall i nest the resources in User and Friendships. This is the way Railscasts used:

devise_for :users
  resources :users, only: [:index, :show] 
  resources :friendships, only: [:create, :destroy]

This is how i used:

devise_for :users

      resources :users, only: [:index, :show] do
      resources :friendships, only: [:create, :destroy]
      end

My real problem is that . I want to use friendships in a way that , signed_in user can check the users list , and add a friend if he is not in the friendslist. Now i can add a friend multiple times. And also ,user can add himself as a friend.

How can i fix this links with if/else statements:

showing a user profile works:

<section>
      <h1>
        <%= @user.username %>
      </h1>

            <%= link_to "Arkadaşlarıma Ekle", friendships_path(:friend_id => @user), :method => :post,class: "btn btn-large btn-primary" %>

      </section>

and herei I cant find the way to show the friend's profile. :

<%  for friendship in @friendships %> 
<%= link_to friendship.friend.username, '#' %>
(<%= link_to 'Sil', friendship, :method => :delete %>)
<% end %>

.. rake routes:

I can understand that , I have to use correct if/elses but i am lost in nesting my resources and routing. . Thanks for explanations..

These are my edits: In my users_controller:

def user_is_friend?(other_user)
 current_user.friendships.find_by_friend_id(other_user.id) 
end

<% unless user_is_friend?(@user) %>
  <%= button_to "Add friend", friendships_path(:friend_id => user), :method => :post %>
<% end %>

Is it correct?

4

1 回答 1

2

我会建议你,在你的用户索引视图中,当你用一个变量用户循环时(for @users do |user|)首先添加一个条件:

<% unless current_user == user %>

--> 这将允许您处理除 current_user 之外的所有用户(即您自己)

然后,您可以这样定义:

<% user_is_friend = current_user.friendships.find_by_friend_id(user.id) %>

如果用户已经在您朋友的列表中,这将是 TRUE

然后,最后一段:

<% if !user_is_friend %>
  <%= button_to "Add friend", friendships_path(:friend_id => user), :method => :post %>
<% end %>
于 2012-07-09T13:28:55.937 回答