Lukas_Skywalker
Lukas_Skywalker

Reputation: 2060

Rails link_to helper relative to namespace

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.

Upvotes: 0

Views: 801

Answers (3)

Tan Nguyen
Tan Nguyen

Reputation: 3376

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

Upvotes: 0

oreoluwa
oreoluwa

Reputation: 5623

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

Upvotes: 1

Okomikeruko
Okomikeruko

Reputation: 1173

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 %>

Upvotes: 0

Related Questions