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)
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 })
YOu could do a join instead so something like:
@categories = Categories.joins(:menu_options).where(:menu_options => {:user_level => user_level})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With