dots in URL routes with namespace rails 3.1

心已入冬 提交于 2019-12-23 18:15:00

问题


I have this in routes.rb

root :to => "posts#index"

  devise_for :users,  :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }

  resources :users, :only => :show

  resources :boards 

  resources :posts do
  resources :comments
  end 

namespace :users do
 resources :posts do
  get :posts, :on => :member
 end
 resources :boards do  
  get :boards, :on => :member
 end  
end      

rake routes:

  boards_users_board GET    /users/boards/:id/boards(.:format)        {:action=>"boards", :controller=>"users/boards"}
        users_boards GET    /users/boards(.:format)                   {:action=>"index", :controller=>"users/boards"}
                    POST    /users/boards(.:format)                   {:action=>"create", :controller=>"users/boards"}
     new_users_board GET    /users/boards/new(.:format)               {:action=>"new", :controller=>"users/boards"}
    edit_users_board GET    /users/boards/:id/edit(.:format)          {:action=>"edit", :controller=>"users/boards"}
         users_board GET    /users/boards/:id(.:format)               {:action=>"show", :controller=>"users/boards"}

If I put this link with 2 parameters:

<% @posts.each do |post| %>
   <%= link_to post.board.name, users_board_path(post.user, post.board) %>
<% end %>

I get the next url with a dot:

http://localhost:3000/users/boards/hyperrjas.board-2

  • hyperrjas is the user_id that I have put with slug :username.
  • I use namespace because are nested resources and I have a panel for users.

My question is: How can I change the dot for slash / in my generated url? should look and work as follows:

http://localhost:3000/users/boards/hyperrjas/board-2


回答1:


Move the user routes below the nested ones. Rails will "catch" the upper routes first.

Your problem is really with the route generation (and some ordering too). If you need to access the users boards, you don't need a namespaced route but a nested one.

If you need /users/:user_id/boards and /users/:user_id/boards/:id you'll need the nested route. Notice that in the second route there are 2 params (user_id and id). If you use a namespaced route, you'll only "need" one (the board id). The second argument would be the format. Notice that in the output from rake routes you only "need" 1 param.

Try the next route to see if it works.

  resources :users do
    # This will give you /users/:user_id/posts
    # and /users/:user_id/posts/:post_id
    # among others
    resources :posts
  end


来源:https://stackoverflow.com/questions/8806981/dots-in-url-routes-with-namespace-rails-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!