electrify electrify - 3 months ago 11
Ruby Question

(Rails) How to find by id and save users into an instance from another model which has user ids?

Apologizes for such a confusing title,

I have 2 models:

User.rb

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :friends
end


Friend.rb

class Friend < ApplicationRecord
belongs_to :user
end


I want to show a list of all friends for a specific user.

Profiles controller:

class ProfilesController < ApplicationController

def show
end

def followed_users
@friends = User.where(id: current_user.friends.friend_id)
end

end


followed_users.html.erb

<% @friends.each do |f| %>
<%= f.email %>
<% end %>


But this doesn't work and I get the following error:

NoMethodError in ProfilesController#followed_users
undefined method `friend_id' for # <Friend::ActiveRecord_Associations_CollectionProxy:0x007fb960747a90> Did you mean? find_index

Answer

Try following

def followed_users
   @friends = User.where(id: current_user.friends.pluck(:friend_id))
end