Routes, Path Helpers, and STIs in Rails 4.0

It drives me crazy! I have two models Lion and Cheetah . Both inherit from Wildcat .

 class Wildcat < ActiveRecord::Base; end class Lion < Wildcat; end class Cheetah < Wildcat; end 

It uses STI.

All of them are processed through the WildcatsController . There I have before_filer to get type wildcat from params[:type] and all other things to use the correct class.

In my routes.rb I created the following routes:

 resources :lions, controller: 'wildcats', type: 'Lion' resources :cheetahs, controller: 'wildcats', type: 'Cheetah' 

If now I want to use the path helpers that I get from the routes ( lions_path , lion_path , new_lion_path , etc.), everything works as expected, except for show and new . For example, lions_path returns the path /lions . The new path returns /lions/new?type=Lion . Same as the show path. When I try to enter /lions/new in my root domain, it correctly adds the type parameter in the background.

So my question is: why does Rails add a type parameter to the URL if I use the path helper? And why only for new and show ?

I am running Rails 4.0.0 with Ruby 2.0 using the new Rails application.

+7
ruby ruby-on-rails ruby-on-rails-4 routes sti
source share
2 answers

Why use type ? Why not use legacy controllers?

 resources :lions resources :cheetahs 

Then

 class LionsController < WildCatsController end class CheetahController < WildCatsController end class WildCatsController < ApplicationController before_filter :get_type def index @objs = @klass.scoped end def show @obj = @klass.find(params[:id]) end def new @obj = @klass.new end # blah blah def get_type resource = request.path.split('/')[0] @klass = resource.singularize.capitalize.constantize end 
+7
source share

I had this problem. You can try to disconnect the server, delete the / tmp directory and restart.

Rails Routes and Controller Settings

-2
source share

All Articles