Kristiyan Tsvetanov
Kristiyan Tsvetanov

Reputation: 1047

Rails, implement options for model

the title sounds strange, so is my problem... I am building a simple app - I have a restaurant model which has_many meals that users can add to their carts as orders(the order model has a meal's id and a quantity). Now, I would like to be able to add options to the meals - e.g. a pizza meal would have "small", "medium", and "large" option which would affect the price of this item. How do you think is the best way to implement this? My problem is that each meal might have different options, and options can have different prices. Therefore, I cannot just add an attribute "option" as a string. On the other hand, if I use another model, there would be too much nesting in the routes which I read is a bad practice:

resources :restaurants do
   resources :meals do
      resources :options
   end
end

How to avoid this? Thank you for any suggestions!!

Upvotes: 0

Views: 57

Answers (1)

trh
trh

Reputation: 7339

There's no reason not to have an options model to hold each of your options as necessary - though you should really consider a shallow route for restaurants as the restaurant itself has nothing to do with options. So instead your routes might look like:

resources :restaurants, shallow: true do
   resources :meals do
      resources :options
   end
end

If you look at your routes now (rake routes) you'll see how much they change.

But its worth considering that you don't need the resources for options. A visitor won't be creating new options. They'll be adding existing options to a collection (meal + option = order .. or something similar) -- so you might only have that route in the admin namespace for creating new options for a menu.

Upvotes: 0

Related Questions