Reputation: 383
I'm new to ruby on rails so please forgive the question. I tried looking at the Rails guide and a few similar questions - and I'm 90% there I feel. Currently, I can pull up the list of users that excludes current user - but my work doesn't exclude the users that I followed which is what I want also. I am trying to show for a specific user a list of users who he or she has not yet followed. I have listed below all my relevant code down below. Thank you so much guys!!
Users controller
def show
@user = User.find(params[:id])
@random = User.find((User.pluck(:id) - [@user.id] - [@user.following.ids]).shuffle.first)
end
Show.html.erb
<div>
<%= image_tag @random.avatar, width: 38, class: "css-style" %> <strong><%= link_to @random.username, @random, class: "youmaylikelink" %></strong>
</div>
Rails Console In my rails console if I do @user.following.ids > I get the ids for the users that the current user is following. That is why I put @user.following.ids in my users controller.
Upvotes: 0
Views: 96
Reputation: 36110
The problem is that @user.following.ids
is already an array, thus there is no need to wrap it in one. Hence:
User.find((User.pluck(:id) - [@user.id] - @user.following.ids).shuffle.first)
Still, this fetches all user ids, which on production database would be problematic. You could instead select only a single record:
User.where.not(id: [@user.id] + @user.following.ids).first
How to do the shuffle is database specific. For postgresql and sqlite3, you could do:
User.where.not(id: [@user.id] + @user.following.ids).order('RANDOM()').first
Upvotes: 1
Reputation: 2786
You can use the below code. No need to find the user as well.
User.where.not(id: [[current_user.id] + current_user.following.ids]).shuffle.first
Upvotes: 1
Reputation: 2183
You should not use find
instead use where
.
If your are using rails 4+
then
User.where.not(id: [[@user.id] + @user.following.ids])
will return all the user excluding @user
and @user.following
Even you can write as User.where.not(id: [[@user] + @user.following])
Now you can make any operation on it. Hope this will help you.
Upvotes: 1