Get Rails Route To Reflect Database Lisiting

- 1 answer

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 %>

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 find_by:

@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.