0

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.

Kasperi
  • 853
  • 7
  • 17
  • I don't know if it helps under your conditions, but why not use the [will_paginate](https://github.com/mislav/will_paginate) gem? – Tamer Shlash Nov 22 '13 at 21:37

2 Answers2

1
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)
AndyV
  • 3,696
  • 1
  • 19
  • 17
  • Good work! This also has one more plus. Since the overall queries is scoped in chain, it will only do a single optimized SQL query over the table while retrieving `@users`. – kiddorails Nov 22 '13 at 22:09
  • Yes, that was the objective. I like breaking the scopes down into smaller focused bits because they are easier to reuse in other contexts. – AndyV Nov 23 '13 at 01:41
0

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)
kddeisz
  • 5,162
  • 3
  • 21
  • 44
  • 1
    He is using `unless` in his view; thus, rejecting those `users` which match the given condition(s). I think, you should be using `reject` instead of `select` here, for that. – kiddorails Nov 22 '13 at 21:43
  • or just negate the conditionals: User.top.select { |user| current_user != user || !current_user.friendling?(user) }.limit(10) – bjhaid Nov 22 '13 at 22:02
  • @bjhaid technically, yes. But that will only make the overall statement a bit unclear for third person => !ruby_convention. :) – kiddorails Nov 22 '13 at 22:07
  • Updated to be reject. – kddeisz Nov 25 '13 at 02:45