Handling has_one nested resource in Rails 3
I got a User model and a About model. The about model is a page where users have more info about them that due its nature is more appropriate to have it on a separate model rather than in the user model.
I want to be able to route it to something like /:username/about and get all the verbs working on that path (GET POST, PUT, DELETE).
/:username/about
/:username/about/edit
/:username/about
This is what I already have
# routes.rb
resources :users do
resources :abouts
end
match ':username/about' => 'abouts#show', :as => :user_about
match ':username/about/add' => 'abouts#new', :as => :user_new_about
match ':username/about/edit' => 'abouts#edit', :as => :user_edit_开发者_如何学Goabout
And in the models I have
# about.rb
belongs_to :user
# user.rb
has_one :about
When I'm doing a post or put to /roses/about It's interpreting It as a show
Started POST "/roses/about" for 127.0.0.1 at Sun Feb 27 16:24:18 -0200 2011
Processing by AboutsController#show as HTML
I'm probably missing the declaration in the routes, but doesn't it get messy declaring each verb for a resource when it's different from the default?
What's the simplest and cleaner way to archive this?
When using a has_one
, it might make sense to declare it as a singular resource in your routes. Meaning
resources :users do
resource :about # notice "resource" and not "resources"
end
And if you want to override the paths for new/edit, add a :path_names
option to the resource/resources-call:
resources :about, :path_names => { :new => 'add', :edit => 'edit' }
The official documentation has lots of other tips and tricks for routing as well.
You can use scope
and controller
blocks to cut down on the verbiage:
scope "/:username" do
controller :abouts do
get 'about' => :show
post 'about' => :create
get 'about/add' => :new
get 'about/edit' => :edit
end
end
which produces:
about GET /:username/about(.:format) {:action=>"show", :controller=>"abouts"}
POST /:username/about(.:format) {:action=>"create", :controller=>"abouts"}
about_add GET /:username/about/add(.:format) {:controller=>"abouts", :action=>"new"}
about_edit GET /:username/about/edit(.:format) {:controller=>"abouts", :action=>"edit"}
精彩评论