Marina Martin
Marina Martin

Reputation: 192

Rails route with dynamic slug followed by child ID

In my model, a Seller has many Items.

The Seller is accessible via its slug, not its ID:

config/routes.rb

get "/:slug", to: "sellers#show"

This works fine.

However, I want each item URL to include its parent slug according to the format /:slug/:id, e.g. /piano_man/5 or /joe_schmoe/344.

The following works:

config/routes.rb

get '/:slug/:id', to: 'items#show'

app/controllers/items_controller.rb

def show
  @item = Item.find(params[:id])
end

But it (clearly) does not change the default Item URL behavior because this code just ignores the :slug part.

How can I make the default URL <%= link_to item %> point to /:slug/:id instead of /items/:id?

Remember that the "slug" is from the parent model Seller, but the ID is from the Item itself.

Upvotes: 0

Views: 552

Answers (1)

Carlos Drew
Carlos Drew

Reputation: 1633

I think you need to name the custom Seller's Item route and then refer to that named route in your use of link_to:

config/routes.rb

get '/:slug/:id', to: 'items#show', as: 'seller_item'

app/views/items/index.html.haml

= link_to item.name, seller_item_path(slug: item.slug, id: item.id)

That should work, as far as I know... There might also be a way to override to_param on your Item model to return slug and id, instead of having to specify them as arguments directly to seller_item_path.

Upvotes: 1

Related Questions