Skip to content

Commit

Permalink
Fix "unknown column" exception (#943)
Browse files Browse the repository at this point in the history
When custom `slug_column` is used along with `history` and
`sequentially_slugged` modules, wrong query was being formed on `Slug`
model.

Query being made - `select friendly_id_slugs."strange name" from artists`
Query which should be made - `select friendly_id_slugs.slug from artists`

This commit fixes it to use default `slug` column in such case.

Co-authored-by: Philip Arndt <git@p.arndt.io>
  • Loading branch information
yogeshjain999 and parndt authored Jan 31, 2021
1 parent d11fb03 commit 2b29ae7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
21 changes: 16 additions & 5 deletions lib/friendly_id/sequentially_slugged.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ def self.setup(model_class)
def resolve_friendly_id_conflict(candidate_slugs)
candidate = candidate_slugs.first
return if candidate.nil?
SequentialSlugCalculator.new(scope_for_slug_generator,
candidate,
friendly_id_config.slug_column,
friendly_id_config.sequence_separator,
slug_base_class).next_slug

SequentialSlugCalculator.new(
scope_for_slug_generator,
candidate,
slug_column,
friendly_id_config.sequence_separator,
slug_base_class
).next_slug
end

class SequentialSlugCalculator
Expand Down Expand Up @@ -83,5 +86,13 @@ def slug_base_class
self.class.base_class
end
end

def slug_column
if friendly_id_config.uses?(:history)
:slug
else
friendly_id_config.slug_column
end
end
end
end
15 changes: 15 additions & 0 deletions test/sequentially_slugged_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,21 @@ def model_class
assert_equal 'test-name-3', record3.slug
end
end

test "should cope with strange column names" do
Journalist = Class.new(ActiveRecord::Base) do
extend FriendlyId
friendly_id :name, :use => [:sequentially_slugged, :history], :slug_column => "strange name"
end

transaction do
record_1 = Journalist.create! name: "Julian Assange"
record_2 = Journalist.create! name: "Julian Assange"

assert_equal 'julian-assange', record_1.attributes["strange name"]
assert_equal 'julian-assange-2', record_2.attributes["strange name"]
end
end
end

class City < ActiveRecord::Base
Expand Down

0 comments on commit 2b29ae7

Please sign in to comment.