Search code examples
ruby-on-railsruby-on-rails-5friendly-id

Rails 5: Can't find record with friendly id


I just add friendly_id to my application and everything works smooth except one line of code gives me an error.

I get the following error when I try to order a wine from my favorites view.

can't find record with friendly id: "#<Wine::ActiveRecord_AssociationRelation:0x6133278>"


  private
  def set_wine
    @wine = Wine.friendly.find(params[:id])
  end

The is the line in my wines view:

<div class="col-md-3 right">
 <%= link_to "Bestellen", wine_path(@wines), class: "btn btn-form" %>
</div>

Solution

  • Can't find record with friendly id: Wine::ActiveRecord_AssociationRelation:0x6133278

    The problem is @wines is a collection, not a single object. So when you have wine_path(@wines), the collection is passed as an id to the controller method while the friendly_id expects a single record. You must change

    <%= link_to "Bestellen", wine_path(@wines), class: "btn btn-form" %>
    

    to

    <%= link_to "Bestellen", wine_path(favorite.wine), class: "btn btn-form" %>
    

    to resolve the error.