Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Created June 19, 2011 19:47
Show Gist options
  • Save stevenharman/1034653 to your computer and use it in GitHub Desktop.
Save stevenharman/1034653 to your computer and use it in GitHub Desktop.
Rails: multiple route parameters w/a single model - can it be done?
ZomgMyThings::Application.routes.draw do
devise_for :users
scope ":username" do
resources :things #=> /some-user-name/things/42
end
get "/:username" => "users#show", :as => :user_profile
root :to => 'pages#home'
end
class Thing < ActiveRecord::Base
belongs_to :user
end
class ThingsController < ApplicationController
before_filter :authenticate_user!
def create
@thing = current_user.things.build(params[:thing])
if @thing.save
redirect_to(thing_path(@thing.user, @thing)) # YUCK!
# I'd much rather be able to do this, as @thing has the user already
redirect_to(thing_path(@thing))
end
end
end
class User < ActiveRecord::Base
has_many :things
def to_param
username
end
end
@stevenharman
Copy link
Author

Is it possible to get rails route helpers to fulfill multiple route parameters with a single model? I'm talking about a use case something like nested resources, with corresponding helpers, except the outer resource isn't really named nor explicit.

Does that even make sense?

I'm shooting for urls like /:username/thing/:id - similar to how GitHub does their URLs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment