Rails link_to helper relative to namespace

时间:2016-07-11 21:23:41

标签: ruby-on-rails

Let's say I have a blog engine with a backend, where the backend routes are namespaced under admin and the frontend under public. Now I would like to share some of the views between the two namespaces.

Is there a DRY way to instruct link_to to generate urls relative to the current namespace (e.g. a link made with posts_path() where the controller is admin/home#index should point to /admin/posts, but the same link under the controller public/home#index should point to /public/posts), so I can use the same view for both controllers?

I see I could solve it using conditionals, and using admin_posts_path and public_posts_path respectively, but that adds a lot of clutter to the views.

3 个答案:

答案 0 :(得分:1)

Something we did in an API project was not to use namespace, rather to use scopes like this:

scope '/:type', constraints: { type: /(admin|public)/ } do
  resources :posts
end

Then in your views, you'd do:

# The :type param should be inferred from the route, but you could be explicit as such:
link_to 'Posts', posts_path(type: params[:type])

That should always link appropriately to your public and admin posts

答案 1 :(得分:0)

Use scope to do it.

Read more: http://guides.rubyonrails.org/routing.html#prefixing-the-named-route-helpers

scope 'admin' do
  resources :posts, as: 'admin_posts'
end
 
resources :posts
# the same to public

答案 2 :(得分:0)

I recommend setting your links as variables in your controllers if you intend to use the same view.

Like so

Admin::PostController < Parent
  def show 
    @post = Post.find(params[:id])
    @posts_link = admin_posts_path #This is the link
    render "shared_path/show"
  end
end

and

Public::PostController < Parent
  def show
    @post = Post.find(params[:id])
    @posts_link = public_posts_path #This is also the link
    render "shared_path/show"
  end
end

and

#in the view path/show.html.erb
<%= link_to "Posts", @posts_link %>