Created
June 19, 2011 19:47
-
-
Save stevenharman/1034653 to your computer and use it in GitHub Desktop.
Rails: multiple route parameters w/a single model - can it be done?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Thing < ActiveRecord::Base | |
belongs_to :user | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
has_many :things | |
def to_param | |
username | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.