Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routes, path helpers and STI in Rails 4.0

This is driving me crazy! I have the two models Lion and Cheetah. Both inherit from Wildcat.

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

STI is used here.

They all get handled through the controller WildcatsController. There, I have a before_filer to get the type of wildcat from the params[:type] and all the other stuff 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 I now want to use the path helpers, that I get from the routes (lions_path,lion_path,new_lion_path, etc.), everything is working as expected, except the show and the new paths. For example lions_path returns the path /lions. The new path returns /lions/new?type=Lion. Same with the show path. When I try to enter /lions/new to my root domain it correctly adds the type param in the background.

So, my question is, why does Rails add the 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 a fresh Rails app.

like image 542
Hiasinho Avatar asked Sep 23 '13 15:09

Hiasinho


People also ask

What is path helper in Rails?

Searching For Missing Route Values Under the hood, Rails path helpers use ActionDispatch to generate paths that map to routes defined in routes.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

What are routes in Rails?

Rails routes stand in the front of an application. A route interprets an incoming HTTP request and: matches a request to a controller action based on the combination of a HTTP verb and the request URL pattern. captures data in the URL to be available in params in controller actions.

How do I see all routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.


1 Answers

Why using type? Why not use inherited 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
like image 82
Billy Chan Avatar answered Oct 22 '22 10:10

Billy Chan