Kasperi
Kasperi

Reputation: 863

Conditions on rendering @users (exclude current_users and users with friend association)

Currently, I'm doing the conditions in the view. I need to do it in model or controller, but haven't found a way to do it that works.

I have a view rendering 10 users via a partial that sorts them by their friends count (all examples simplified):

Index.html.erb

<%= render @users %>

_partial.html.erb

<% unless current_user == user or current_user.friending?(user) %>
  <%= user.name %>
<% end %>

models/user.rb

scope :top, :order => "friends_count DESC"

users_controller.rb/index

@users = User.top.limit(10)

But in my case, it checks the validations in the partial for each user. How can I do it more effectively in the scope or controller and check for all?

Thanks greatly for all answers. Hugely appreciated.

Upvotes: 0

Views: 81

Answers (2)

kddeisz
kddeisz

Reputation: 5192

When you're getting your @users in the controller, you can use #select.

@users = User.top.reject { |user| current_user == user or current_user.friending?(user) }.limit(10)

Upvotes: 0

AndyV
AndyV

Reputation: 3741

class User
  scope :top, order("friends_count DESC")
  scope :skip_user, lambda{|user| where("id != ?", user.id) }
  scope :skip_user_friends, lambda{|user| where("friend_id != ?", user.id }
end

users_controller.rb

@users = User.top.skip_user(current_user).skip_user_friends(current_user).limit(10)

Upvotes: 1

Related Questions