4

I have a model, and in accordance with the friendly_id gem it looks like this:

class FinancialYear < ApplicationRecord
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  def slug_candidates
    [
        :end_year,
        [:end_year, :max_id]
    ]
  end

  def should_generate_new_friendly_id?
    self.slug.blank? || self.year_changed?
  end

  def end_year
    if !self.year.nil? && self.year.length > 1
      self.year.split('-')[-1].strip
    else
      self.year
    end
  end

  def max_id
    FinancialYear.where(year: end_year).count + 1
  end

end

What it's supposed to do is turn a year:'1999-2000' into a slug: '2000' and 2000-2...etc to avoid collisions.

Unfortunately my tests are failing expected: "2000", got: "2000-f7608e8b-a2e7-449c-ae54-4785c7a68dec"

I am using friendly_id on another model in my app and am using the same technique, and its working perfectly. Any help or suggestions as to why this isn't working would be very appreciated.

UPDATE After more experimentation I've discovered that this seems to only be happening in my rspec tests - but I don't understand why? Any thoughts?

Ash
  • 24,276
  • 34
  • 107
  • 152
  • Here `friendly_id :slug_candidates, use: :slugged` you're saying to use `slug_candidates` method to set slugs, but you didn't posted it Have you defined it? – mrlew Feb 10 '17 at 01:39
  • opps, updated the question – Ash Feb 10 '17 at 01:56
  • I reproduced your setup here (ad the same code) and encountered no errors. The slugs where being set with `2000-2`, `2000-3`, `2000-4`. Maybe the problem is somewhere else. Print: http://imgur.com/a/TLvB4 – mrlew Feb 10 '17 at 02:12
  • I think this is only happening in my rspec tests....but still, why? – Ash Feb 14 '17 at 02:57
  • @Ash can you post your rspec? – David John Smith Feb 16 '17 at 23:07
  • 3
    Maybe `max_id` is returning nil in your tests and friendly_id falls back to the uuid. That would happen if previous FinancialYears aren't being persisted. – Alexandre Angelim Feb 17 '17 at 00:16
  • I can't replicate either. I tested in rspec. can you post your rspec tets? – Edmund Lee Feb 17 '17 at 18:00

1 Answers1

3

i had the same issue,i resolved it by deleting all slug values first and then re-running my save.

###delete all slug values
 User.update_all(:slug=>nil) 

###re-run to get the new slug candidate affective overriding the default alpanumeric slug
 User.find_each(&:save)

Hope it helps.

Milind
  • 4,535
  • 2
  • 26
  • 58