friendly_id icon indicating copy to clipboard operation
friendly_id copied to clipboard

use friendly_id only in frontend not in admin

Open krismp opened this issue 11 years ago • 1 comments

can I use friendly_id generated slug only in front end not in admin

_note: Im not using ActiveAdmin_

in my admin controller:

  def find_data
    @product = Product.find(params[:id])
  end

in my frontend controller:

  def set_data
    @product = current_user.products.friendly.find(params[:id])
  end

Both code still return the same result (using friendly_id generated slug)

class Product < ActiveRecord::Base

extend FriendlyId

friendly_id :name, use: [:slugged, :finders, :history]

private

  def should_generate_new_friendly_id?
    new_record? || slug.blank? || name_changed?
  end

How to accomplished this?

krismp avatar Sep 16 '15 09:09 krismp

One option:

Use the route helpers directly wherever you want to build a URL with the numeric id.

link_to @product # will link to: "/products/my-product-name"
link_to product_path(@product.id) # will link to: "/products/23"

Another option:

If you're using Rails admin or some other library that makes it impractical for you to do this, and if the "friendly" URLs are only used in a few places, then you may wish to override to_param in your model(s) to return the numeric id:

def to_param
  id.to_s
end

Then, in the places where you want the friendly_id, use the route helper method and pass in the slug:

link_to @product # will link to: "/products/23"
link_to product_path(@product.friendly_id) # will link to: "/products/my-product-name"

There are other ways to accomplish this, but this is a start. There has been discussion of this topic before, search the closed issues for more info.

There have been a few discussions about this in the past, take a look through the closed issues for more ideas.

norman avatar Sep 16 '15 13:09 norman