I have the following two classes:
class Menu < ActiveRecord::Base
has_many :menu_headers
accepts_nested_attributes_for :menu_headers
end
class MenuHeader < ActiveRecord::Base
belongs_to :menu
end
Here’s the quetsion:
I am populating via a json file:
{"name":"Dinner Menu","internal_notes":"dinner menu","location_name":"test-loc",
"menu_headers_attributes":
[
{"name":"ceviches"}
{"name":"dim sum"}
]
}
I have a sort value in the menu_header value. If there is not a sort value, it should auto_increment so that the previous json looks like this:
dinner menu
-ceviches sort 0
-dim sum sort 1
I’m assuming in the MenuHeader I could create a before_create to set default values. I’d like something like:
h=MenuHeader.where('menu_id=?',self.associated_model.id).order('sort desc').first
How could I determine the menu_id in the menu_header class? Would this even be available?
thx
Edit: It’s possible to also do this after the insert as an after_create but that just doesn’t seem right.
I’d do it using acts_as_list:
If there’s a reason you want to maintain your own list handling (not a terribly complicated thing), digging into the source and doing it however acts_as_list does would most likely be good; they’ve probably iterated on the idea a couple times.