嵌套路由的URL中的用户名

时间:2013-06-28 17:43:54

标签: ruby-on-rails ruby

我是一个新的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(例如)发送到/ username / posts / 18。

所以基本上,我在问是否有办法做这样的事情:

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

感谢您的帮助!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

希望第一个会奏效。我自己没试过,所以原谅我,但我很确定,一般来说,范围就是你想要的。