Sutto / slugged

Super simple slugs for ActiveRecord 3+, with slug history. Formerly known as Pseudocephalopod.
MIT License
86 stars 16 forks source link

Add a way to disable cached_slug in certain paths helpers #23

Open DavidBennettPIO opened 10 years ago

DavidBennettPIO commented 10 years ago

Hi Guys,

I'm looking for a way to use the id instead of the slug in certain path helpers.

Namely I want admin_posts_path post to generate /admin/posts/2 and not /admin/posts/my-cool-post

So far I have come up with a ugly solution of overriding the to_param for each model in the admin controller and then back again..

class Admin::AdminController < ApplicationController

  before_action :dont_slug
  after_action :do_slug

  private

  def dont_slug

    Post.class_eval do
      def to_param
        self.id.to_s
      end
    end

  end

  def do_slug

    Post.class_eval do
      def to_param
        self.cached_slug.to_s
      end
    end

  end

end

But this is really ugly when you have 10 models using slugs.

I do know I could override each of the path helpers... but I have hundreds of paths and adding one for each route is prone to errors.

Any help with a better work-around would help me a lot!

Thanks!

Sutto commented 10 years ago

Hi there,

I'd really highly suggest against that approach, as it is not threadsafe and very, very inefficient.

If you need to do that (I suggest against switching like that), I suggest using Thread.current to store a boolean flag and having to_param of the post class choose based on the presence of that flag.

Alternatively, my primary suggestion is just to manually specify it, OR override the helpers (e.g. admin_posts_path uses .id instead of to_param)

DavidBennettPIO commented 10 years ago

Hi @Sutto,

Yeah, I decided against that, What I'm doing now is passing to_param: false to is_sluggable in all of my models, then overriding all the non-admin path helpers with cached_slug.

This way I only had to override 20 paths instead of the 150~ on the admin.

I just need to remember to keep these paths up to date if I change my routes. (Writing tests to make sure it doesn’t show the id now)