开发者

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 itera开发者_如何学Goting 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})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜