Get Rails Route To Reflect Database Lisiting
I currently have a page that searched through a listings database. On clicking a selection, the view links to that listing's show page:
<div class="listings_wrapper"> <% @listings.each do |listing| %> <%= link_to listing_url(listing), class: "listing_link" do %> <div class="listing"> <div class="picture"> <% if listing.thumbnail != nil %> <%= image_tag(listing.thumbnail, class: "list_image") %> <% end %> </div>
The show page that is currently routed as:
get 'listings/:listing_id', to: 'listings#show', as: 'listing'
which will get me the address
localhost3000/listing/612983618 (arbitrary id)
What I'm trying to do is get the route to display information from the database in the route instead, for SEO purposes:
When I try to adjust to
get 'listings/:listing_id', to: 'listings#show', as: 'listing/:address/:booking_id'
I get blocked on loading. I've been looking around stackoverflow at similar answers, but haven't got my head around this problem as of yet. Since the link is pulling the object itself, and the route is pulling the id from that, it would make sense to refer to the :address key instead, but something is clearly missing. Help?
In order to make the URI for
listings#show to receive the address and booking_id of the object, then you could move the alias in your route definition to the uri argument, like:
get 'listing/:address/:booking_id', to: 'listings#show'
Now it'll be waiting both attributes. While in your controller if you want to find that specific object from both sent attributes, then you can use
@listing = Listing.find_by(adress: params[:address], booking_id: params[:booking_id]) @listings = Listing.last(3)
Note this will work, but in case you have more than one record with same address and booking_id, find_by will just return the first one.
- → Trigger a click with jQuery using link_to of rails 4
- → Adding html data attribute to simple_forms input
- → How to remove parameters from the root URL if it does I18n
- → passing parameters to rails back end from an ajax call
- → Blocking ?page= in robots.txt
- → react js and rails Updating state on a component with active record relationship
- → State not passed into prop
- → Cannot read property 'modalIsOpen' of undefined
- → Objects not valid issue
- → How to map API params to model
- → Consuming webhooks shopify-api
- → How to add ScriptTag on shopify_api gem?