2013-06-28 55 views
2

我是一個新的rails開發者,在我有一個用戶配置文件,如:localhost:3000/posts路由到localhost:3000/Charles其中Charles是用戶名。用戶名在嵌套路由的網址

所以我使用要做到這一點的代碼如下所示:

的routes.rb

match "/:username" => "posts#index" 

,然後在我的控制器:

@user = User.find_by_username params[:username] 
@search = Post.search do |query| 
    query.fulltext params[:search] 
    query.with(:user, @user.id) 
end 

這只是爲了偉大工程帖子索引,但我想有帖子/ 18(例如)被路由到/用戶名/帖子/ 18。

所以基本上,我問,如果有一種方法可以做這樣的事情:

match "/:username" => "posts#index" do 
    resources :posts 
end 

感謝所有幫助!

回答

1

嘗試

scope ':username' do 
    resources :posts 
end 

bundle exec rake routes

posts GET /:username/posts(.:format)   posts#index 
      POST /:username/posts(.:format)   posts#create 
new_post GET /:username/posts/new(.:format)  posts#new 
edit_post GET /:username/posts/:id/edit(.:format) posts#edit 
    post GET /:username/posts/:id(.:format)  posts#show 
      PUT /:username/posts/:id(.:format)  posts#update 
      DELETE /:username/posts/:id(.:format)  posts#destroy 
+0

,將讓你/職位/ 1 /查爾斯,和/職位/查爾斯,他希望/查爾斯/職位/ 1 – GoGoCarl

+0

@ Pierre-Louis Gottfrois,謝謝! –

1
match "/:username/posts/:id" => "posts#show" 

但是,這不會真正幫助時,你需要編輯和這樣的。因此,嘗試:

scope "/:username" do 
    resources :posts 
end 

不及格的:

scope "/:username" do 
    get '' => "posts#index" 
    get 'posts/:id' => "posts#show" 
end 

希望第一個將工作。沒有嘗試過,所以原諒我,但我敢肯定,一般來說,範圍是你想要的。

2

scope '/:username' do 
    resources :posts 
    end 

產生你想要什麼:

posts GET /:username/posts(.:format)   posts#index 
      POST /:username/posts(.:format)   posts#create 
new_post GET /:username/posts/new(.:format)  posts#new 
edit_post GET /:username/posts/:id/edit(.:format) posts#edit 
    post GET /:username/posts/:id(.:format)  posts#show 
      PATCH /:username/posts/:id(.:format)  posts#update 
      PUT /:username/posts/:id(.:format)  posts#update 
      DELETE /:username/posts/:id(.:format)  posts#destroy