patternrubyrailsMinor
Simpler method to find users in child categories
Viewed 0 times
methodsimplerchildfindcategoriesusers
Problem
I am using the ancestry gem to organize my post categories tree.
I have 8 parent categories, and they all have many child categories.
To retrieve an array of child categories, I use:
I defined these relations in my
The last relation allows me to find the users who post in each category.
What I am trying to do: on first login, users have to choose their categories of interest. On the next screen, they are suggested users who post in the categories they chose.
To find the suggested users, I wrote a method:
This works, but it seems overly complicated. Is there any way to do this in a "best practice" way ?
I have 8 parent categories, and they all have many child categories.
To retrieve an array of child categories, I use:
parent_category.childrenI defined these relations in my
category model:has_ancestry
has_many :posts
has_many :users, through: :postsThe last relation allows me to find the users who post in each category.
What I am trying to do: on first login, users have to choose their categories of interest. On the next screen, they are suggested users who post in the categories they chose.
To find the suggested users, I wrote a method:
def recommendations
@users = []
(current_user.get_voted Category).each do |category|
category.children.each do |cat|
@users << cat.users
end
end
@users = @users.flatten.uniq
endThis works, but it seems overly complicated. Is there any way to do this in a "best practice" way ?
Solution
Some notes:
I'd write:
ys = []+xs.each+ys.push+ys.flattenThat's an imperative and pretty verbose pattern. A functional approach would use flat_map.
@users = @users.flatten.uniq. Don't re-use variables. Different values, different variables.
(current_user.get_voted Category). You saved two parens on the function call at the cost of being forced to write them to wrap the expression. It's not worth it. I'd just use parens on calls except in DSL-style statements. Check https://github.com/bbatsov/ruby-style-guide
I'd write:
def recommendations
@users = current_user.get_voted(Category).
flat_map { |category| category.children.flat_map(&:users) }.
uniq
endCode Snippets
def recommendations
@users = current_user.get_voted(Category).
flat_map { |category| category.children.flat_map(&:users) }.
uniq
endContext
StackExchange Code Review Q#123106, answer score: 2
Revisions (0)
No revisions yet.