Module: Spree::Core::Permalinks

Extended by:
ActiveSupport::Concern
Defined in:
lib/spree/core/permalinks.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/spree/core/permalinks.rb', line 40

def save_permalink(permalink_value=self.to_param)
  self.with_lock do
    permalink_value ||= generate_permalink

    field = self.class.permalink_field
      # Do other links exist with this permalink?
      other = self.class.select(field).where("#{self.class.table_name}.#{field} LIKE ?", "#{permalink_value}%")
      if other.any?
        # Find the existing permalink with the highest number, and increment that number.
        # (If none of the existing permalinks have a number, this will evaluate to 1.)
        number = other.map { |o| o.send(field)[/-(\d+)$/, 1].to_i }.max + 1
        permalink_value += "-#{number.to_s}"
      end
    write_attribute(field, permalink_value)
  end
end