CaptainCarl
CaptainCarl

Reputation: 3489

Nested resources linking

I have a category with a subcategory and the subcategory has posts. I'd like to link it as following:

/categoryname/subcategoryname/post_id/postname

I've tried doing so by putting this in my routes:

  resources :categories do
    resources :subcategories do
      resources :posts
    end
  end

But any time I'd like to create a link for my subcategories (/categoryname/subcategory/) via link_to(subcat.name, category_subcategory_path)

I get:

No route matches {:controller=>"subcategories", :action=>"show"} missing required keys: [:category_id, :id]

How would I approach this to get the desired link setup?

Thanks in advance,

Upvotes: 1

Views: 164

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

Slugs

Firstly, if you're looking to use slugged routes, you'll be best looking at gems including friendly_id or slugalicious -- basically allows you to manage "slugs" for your models -- saving titles or other attributes in URL encoded format


Paths

Secondly, I think you'll resolve your issue by providing values, rather than using the path helper. I would do this:

link_to subcat.name, category_subcategory_path(category.id , subcat.id)

When you use a path helper, it only cares about which params you send. The path helper you're using requires you to set the category_id and subcategory_id params -- which you should pass to the path helper as demonstrated above

This will create the path using id's - if you'd like to use slugs, you'll need to use one of the aforementioned gems (friendly_id is recommended) to set up the slugs in your app

Upvotes: 1

Related Questions