Reputation: 932
I'm having an issue trying to get a link_to working after changing routes on my app. This may be a simple one but I honestly cannot see just linking to link_to with the object name will not work as previously did before the route changed.
Background: I'm using friendly_id gem (not sure if i still need this after making changes to the url manually). I'm also using Ancestory gem in there too.
On the front facing app. I've a listings resource that is only used for index and show. See below routes and also previous working route.
# Front facing resources
scope "/:category_name/:category_id" do
resources :listings, only: [:show], path: '/:title'
end
resources :listings, only: [:index]
before (working fine)
# Front facing resources
resources :listings, only: [:index, :show]
resources :auctions, only: [:index, :show]
I've been successful making my url show a result of:
listing GET /:category_name/:category_id/:title/:id(.:format) listings#show
result:
http://localhost:3000/listings/helicopter/test-one/4
This will do for now. I'm still trying to figure the end url. So I can create the listing and view it my manually typing the url into the browser.
The error occurs when I'm viewing the Index page of the listings and I have a link_to
current code:
<%= link_to listing.title, listing %>
Error:
No route matches {:action=>"show", :controller=>"listings"}, missing required keys: [:category_id, :category_name, :id, :title]
What way do I go about adding these required keys to the link_to helper? I've tried lots of ways but not far. I presumed changing just the show route would not have messed too much with any previous controller methods and that the listing would still be found by id.
Any direction would be great. Thanks a million.
*** UPDATE ****
Ok so before sending the above I had a closer look and got it working however I'm asking is there a cleaner way to do this? It just doesn't look very "The Rails way". My end goal is to have a long SEO friendly link that contains category and possibly subcategories.
Working code:
<%= link_to listing.title, listing_path(category_name: "listings", category_id: listing.category.name, title: listing.title.parameterize, id: listing.id) %>
Result:
http://localhost:3000/listings/Aircraft/twin-piston-jet/1
Thoughts please???
Upvotes: 1
Views: 106
Reputation: 2283
You could use helpers for that https://api.rubyonrails.org/classes/ActionController/Helpers.html
app/helpers/listing_helper.rb
module ListingHelper
def listing_route(listing, category_name = "Listings")
listing_path(category_name: listing, category_name: listing.category.name, title: listing.title.parameterize, id: listing.id)
end
end
On your views
<%= link_to listing.title, listing_route(listing) %>
Upvotes: 1