0

I installed friendly_id according to the instructions. And use it for products. For show i use:

@product = Product.friendly.find(params[:id])

And it works. But I have a couple of question, on its use for other controllers. In cart_item_controller i use:

@cart_item = current_user.cart.cart_items.find_by(product_id: params[:product_id])

I changed it to:

@cart_item = current_user.cart.cart_items.friendly.find(params[:id])

But i get error

undefined method `friendly' for #<ActiveRecord::Associations::CollectionProxy []> Did you mean? friendly_id?

How do I properly replace this so that it works? Also, for comments i use:

  def set_product
    @product = Product.find(params[:product_id])
  end

I tried replacing this with:

@product = Product.friendly.find(params[:id])

But getting an error:

Couldn't find Product without an ID
SsPay
  • 161
  • 9
  • 1
    I would only use friendly id where you actually need it for vanity urls. Like say `/users/bob` or `/products/iphone6`. Its not meant to replace the finders everywhere in your application as a straight primary key look is much faster than `WHERE id = ? OR slug = ?`. It gets even more messy if you have slug history as then it has to join a seperate table as well. – max Jan 21 '20 at 20:12
  • @max This is my homework :) I must do it :) – SsPay Jan 21 '20 at 20:17
  • 1
    Then you would need to do something like `current_user.cart.cart_items.find_by(product_id: Product.friendly.find(params[:product_id]))`. – max Jan 21 '20 at 20:25
  • 2
    "Couldn't find Product without an ID" means that `params[:product_id]`is nil and really has nothing to do with friendly id. – max Jan 21 '20 at 20:27

0 Answers0