Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix(Slugged+History+Scoped): fix SQL errors when using the 3 plugins together #625

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions lib/friendly_id/history.rb
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,14 @@ def slug_history_clause(id)
def scope_for_slug_generator
relation = super
return relation if new_record?
relation = relation.merge(Slug.where('sluggable_id <> ?', id))

# joins(:slugs) is needed but will be added to the relation by `exists_by_friendly_id?`
sw = Slug.where('sluggable_id <> ?', id)
if friendly_id_config.uses?(:scoped)
relation = relation.where(:scope => serialized_scope)
# scope is in Slug not in the model table
sw = sw.where(:scope => serialized_scope)
end
relation
relation.merge(sw)
end

def create_slug
Expand Down
38 changes: 38 additions & 0 deletions test/history_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,44 @@ class Restaurant < ActiveRecord::Base
end
end

class HistoryTestWithSlugScopeAutomaticRegen < HistoryTest

class Restaurant < ActiveRecord::Base
extend FriendlyId
belongs_to :city
friendly_id :name, :use => [:slugged, :scoped, :history], :scope => :city

def should_generate_new_friendly_id?
slug.blank? or name_changed?
end
end

def model_class
Restaurant
end

test 'should allow reversion back to a previously used slug and recreation based on name when blank' do
city = City.create!
with_instance_of(model_class, name: "My #{rand(1000)} name", city_id: city.id) do |record|
record.name = 'bar'
record.save!
assert_equal 'bar', record.friendly_id
record.name = 'foo'
record.save!
assert_equal 'foo', record.friendly_id

record.slug = 'something-else'
record.save!
assert_equal 'something-else', record.friendly_id

record.name = 'whatever'
record.slug = nil
record.save!
assert_equal 'whatever', record.friendly_id
end
end
end

class City < ActiveRecord::Base
has_many :restaurants
end
Expand Down