Rails: different controller behavior based on route

I am looking for best practice to solve the following situation:

I have an “additive” model, which should be many-to-many, related to 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 

Routes are nested as follows:

 resources :offers do resources :additives end resources :meals do resources :additives end 

So, I get the urls like this:

 /offers/123/additives /meals/567/additives 

Both routes lead to the same controller action as additives#index . In AdditivesController, I check to see if options are available to select the data to retrieve:

 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 deal with this problem? It works very well, but I'm not sure if these are rails ... Thanks for your answers!

+4
source share
2 answers

switching sigh to answer-space, so I can at least add a carriage return and make the code dumb.

I agree with the answer of fl00r, but add that you need to instantiate the object this way:

 @type = params[:type] @obj = @type.constantize.find(params["#{type}_id"]) @additives = @obj.additives 
+1
source

EDIT regarding @Taryn East

 resources :offers do resources :additives, :type => "Offer" end resources :meals do resources :additives, :type => "Meal" end class AdditivesController < ApplicationController before_filter :find_additive def index @additives = @additive.additives end private def find_additive @type = params[:type] @additive = @type.constantize.find([@type, "id"].join("_")) # or "#{@type}_id", as you wish end end 
+1
source

All Articles