User friendships Nesting logic in Rails 3

130 views Asked by At

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?

1

There are 1 answers

3
citraL On BEST ANSWER

I would recommend you, in your user index view, when you are looping with a variable user (for @users do |user|) to add first a condition:

<% unless current_user == user %>

--> this will allow you to process all users except the current_user (i.e. yourself)

Then, you can define this:

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

This will be TRUE if the user is already in your friend's list

And then, a last piece:

<% if !user_is_friend %>
  <%= button_to "Add friend", friendships_path(:friend_id => user), :method => :post %>
<% end %>