I’m looking for the best practice to solve the following situation:
I’ve got an “Additive” Model which should be many-to-many-associated with some other models.
Examples:
# Meal-Model
has_and_belongs_to_many :additives
# Offer-Model
has_and_belongs_to_many :additives
# Additive-Model
has_and_belongs_to_many :meals
has_and_belongs_to_many :meals
The routes are nested in the following way:
resources :offers do
resources :additives
end
resources :meals do
resources :additives
end
So I get URLs like this:
/offers/123/additives
/meals/567/additives
Both routes lead to the same controller action, which is additives#index. In the AdditivesController I check if params are available to choose which data to fetch:
class AdditivesController < ApplicationController
before_filter :offermealswitch
# GET /restaurants/1/meals/123/additives
# GET /restaurants/1/offers/123/additives
def index
@additives = @additivemeal.additives
end
def offermealswitch
if params.has_key?(:meal_id)
@additivemeal = Meal.find(params[:meal_id])
@type = "Meal"
elsif params.has_key?(:offer_id)
@additivemeal = Offer.find(params[:offer_id])
@type = "Offer"
end
end
end
Is this the right way to handle that problem? It works very well, but I’m not shure this is the rails way…
Thanks for your answers!
sigh switching to answer-space so I can at least add carriage returns and make the code not dumb.
I agree with fl00r’s answer, but would add that you’d need to instantiate the object thus: