0

I'm using the gem Friendly ID, and I currently have to do 2 saves in order to save the slug.

It doesn't seems right to me.

class Contractor < ActiveRecord::Base
  include FriendlyId
  friendly_id :slug_candidates, use: :slugged, slug_column: :alias
  after_commit :generate_new_alias, unless: Proc.new {|contractor| contractor.business_name_changed? }


  def slug_candidates
      [
        :business_name,
        [:business_name, :city],
        [:business_name, :city, :state]
      ]
  end

  def generate_new_alias
    if self.alias != self.alias_was
      self.alias = nil
      self.save
    end
  end

end

Any idea what I'm doing wrong ?

bl0b
  • 926
  • 3
  • 13
  • 30
  • why would you do that? is that recommended by friendly id? looks like a bad practice. – phoet Mar 13 '14 at 04:56
  • I don't really understand why you are using the generate_new_alias method. I would ditch that method and remove slug_column: :alias and the after_commit call. – rails4guides.com Mar 13 '14 at 07:01
  • @rails4guides.com If I remove the `slug_column: :alias` then friendly_id has no idea which column to check for slugs. And if i remove the after commit it never re-generate the alias. – bl0b Mar 13 '14 at 15:07
  • Well, I've used it without having to specify an alias. Did you follow these instructions: https://github.com/norman/friendly_id ? – rails4guides.com Mar 13 '14 at 15:38
  • @rails4guides.com well, we use a levacy database so, I have no choice but to specify wich column to use. Also the instructions says `Slugs are no longer regenerated when a record is saved. If you want to regenerate a slug, you must explicitly set the slug column to nil` but if I do so on a before_commit I have a mysql error because alias cannot be null. – bl0b Mar 13 '14 at 16:05
  • Perhaps it's not possible for your use case. Personally, what you are doing with alias seems a bit fuzzy to me. – rails4guides.com Mar 13 '14 at 16:29
  • Alias is a slug column from our legacy database. – bl0b Mar 13 '14 at 16:39
  • Just a small change for the sake of readability. `self.alias != self.alias_was` is the same as `self.alias_changed?` – Matenia Rossides Mar 17 '14 at 00:09

0 Answers0