Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR 3 - Finding a list of parents from group of children

I have two models with a typical relationship:

menu_options model:

class MenuOption < ActiveRecord::Base
  belongs_to :category
end

categories model:

class Category < ActiveRecord::Base
  has_many :menu_options
end

I'm displaying categories in a partial, and then the menu_options in another partial. I am currently skipping the empty categories by iterating through the menu_options and collecting all the categories that show up with this code:

@menu_options = MenuOption.select_by_user_level(user_level)
categories = []
@menu_options.each do |m|
 categories << m.category
end
@categories = categories.uniq

I've been using similar ways of doing this for quite a while, I am wondering if there's a more rails way to do this?

**SOLVED: I neglected to mention that the method 'select_by_user_level' was using inequalities. I took the code you had both provided, and updated it to get rid of that method, and combined the .uniq into the line for selecting categories. Here's the result. Thanks for your help!

@categories = Category.joins(:menu_options).where('menu_options.minimum_user_level <= ?', @user.user_level ).uniq
@menu_options = MenuOption.where('minimum_user_level <= ?', @user.user_level)
like image 476
Nic Avatar asked Jan 19 '23 08:01

Nic


2 Answers

You can simply select Categories which have a menu_option with :user_level = user_level using

@categories = Categories.joins(:menu_options).where(:menu_options => { :user_level => user_level })
like image 170
Dogbert Avatar answered Jan 21 '23 23:01

Dogbert


YOu could do a join instead so something like:

@categories = Categories.joins(:menu_options).where(:menu_options => {:user_level => user_level})
like image 34
Kyle d'Oliveira Avatar answered Jan 21 '23 21:01

Kyle d'Oliveira