在 Rails 3 中处理 has_one 嵌套资源 [英] Handling has_one nested resource in Rails 3
问题描述
我有一个 User 模型和一个 About 模型.about 模型是一个页面,用户可以在其中获得更多关于他们的信息,由于其性质,将其放在单独的模型中而不是用户模型中更合适.
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.
我希望能够将其路由到/:username/about 之类的内容,并让所有动词都在该路径上工作(GET POST、PUT、DELETE).
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
这是我已经拥有的
# 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_about
在我拥有的模型中
# about.rb
belongs_to :user
# user.rb
has_one :about
当我在发帖或发到/roses/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?
推荐答案
您可以使用 scope
和 controller
块来减少冗长:
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
产生:
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"}
这篇关于在 Rails 3 中处理 has_one 嵌套资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!