tfantina
tfantina

Reputation: 815

Is there a more concise way to get attributes from a parent model

I'm setting up a self-referential User model for adding friends. I have a User model that has_many :friend_requests. When a user adds a friend a record is created in the friend_request model which has the user_id and the friend_id.

I can list all the requested friend_ids from the friend_request model but I can't figure out how to easily turn those ids back into usernames without an ugly loop like this in the view:

  <% for user in @user.friend_requests %>
    <% @usr = User.where(id: user.friend_id) %>
    <% @usr.each do |usr| %>
      <%= usr.username %>
    <% end %>
  <% end %>

This is the friend_request controller:

 def index
        @incoming = FriendRequest.where(friend: current_user)
        @outgoing = current_user.friend_requests
        @user = current_user
end

Is there a simpler way to get the user's name from the Users table without looping through all the friend_ids in the friend_request table

Upvotes: 0

Views: 119

Answers (2)

Vasilisa
Vasilisa

Reputation: 4640

It is code from one of my projects, I use Friendship instead of FriendRequest

class User < ActiveRecord::Base
  has_many :friendships, dependent: :destroy
  has_many :friends, through: :friendships
  has_many :user_followers, class_name: 'Friendship', foreign_key: 'friend_id', dependent: :destroy
  has_many :followers, through: :user_followers, source: :user
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, class_name: "User"
end

In controller @friends = current_user.friends. And then in view just two lines

<% @friends each do |user| %>
  <%= user.username %>

Upvotes: 0

Gleydson S. Tavares
Gleydson S. Tavares

Reputation: 600

I think you should create a "has_many: through"

class Friends < ApplicationRecord
  belongs_to :user
  belongs_to :friend_requests, class_name: 'User'
end

class User < ApplicationRecord
  has_many :friends
  has_many :friend_requests, through: :friends
end


@user.friend_requests << @other_user
@other_user.friend_requests << @user

@user.friend_requests.delete @other_user
@other_user.friend_requests.delete @user

Upvotes: 1

Related Questions