deadkarma
deadkarma

Reputation: 3144

How to order a has_many association by a column on the join table

Given the following models:

class Menu < ActiveRecord::Base
  has_many :items
end

class Items < ActiveRecord::Base
  has_and_belongs_to_many :menus
end

Each menu needs to have a separate sort order for it's items

I'd normally add a sort_order column on the join table menus_items

Do I need to create a new model to store this info and add a :through relationship?

What's the best way to set this up in Rails?

Upvotes: 2

Views: 756

Answers (1)

ry.
ry.

Reputation: 8055

Yep, you'll need to create a new MenuItem class and associated menu_items table.

class Menu
   has_many :menu_items, :order => 'sort_order'
   has_many :items, :through => :menu_items
end

class MenuItem
   belongs_to :menu
   belongs_to :item
end

class Item
   has_many :menu_items
   has_many :menus, :through => :menu_items
end

Your menu_items table should have a column for menu_id, item_id, and sort_order (or whatever you are using as the name of your sorting column). Remember though, you need to handle the setting of sort_order. You could use the acts_as_list plugin or roll in the logic yourself, depending on your requirements.

Upvotes: 2

Related Questions