0

I have the following models:

class Article < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
end

Articles are nested under categories like this:

resources :categories, only: [] do
  resources :articles, only: [:show]
end

which gives me the following route

GET /categories/:category_id/articles/:id   articles#show

To use this in my views do i need to write

link_to category_article_path(article.category, article)
  # => "/categories/1/articles/1 

Their isn't any article_path, all articles will always be nested under the associated category. However i was wondering if their is a way for me to DRY this up so i could simply write

link_to article_path(article)
  # => "/categories/1/articles/1 

and still have the route nested, under category.

I know that i could just write a helper or something similiar, but i would like a more general solution, because i know that i would get more nested resources under categories at some point (like blogs, videos, etc.) that all has a belongs_to relation to the categories.

So basically am I looking for something like this

# Example, doesn't work (article_id is not available here):
resources :categories, only: [] do
  resources :articles, only: [:show], defaults: { category_id: Article.find(article_id).category.id }
end

However that doesn't work, as article_id isn't available in the defaults block. As far as i know, can you only create static default values, and i need a dynamic one based on the current article.

jokklan
  • 3,520
  • 17
  • 37

1 Answers1

1

You can achieve what you want by aliasing your resource like you would do in a normal route.

resources :categories, only: [] do
  resources :articles, only: [:show], defaults: { category_id:Article.find(article_id).category.id }, as: 'article'
end

Now you can use article_path(article) instead of category_article_path

Serdar Dogruyol
  • 5,147
  • 3
  • 24
  • 32