我使用FriendlyId处理我的slu and,到目前为止一直很好。
我创建了一个{name: "first name"}
的模型,我的slug是
使用slug_candidates
自动生成。
这是代码的一部分
ruby
...
friendly_id :slug_candidates, :use => [:scoped, :history], :scope => :company
...
private
def slug_candidates
[:slug, [:name]]
end
history
模块ruby
model_a = {name: "Model A", slug: "model-a"}
更新也有效
ruby
model_a = {name: "Model A", slug: "model-b"}
ruby
model_a = {name: "Model A", slug: "model-c"} # just changed the name of the slug
发现也适用于历史
ruby
GET api/v1/models/model_a returns model_a
GET api/v1/models/model_b returns model_a
GET api/v1/models/model_c returns model_a
我希望能够做到以下
使用旧(历史)slug创建一个新模型。 ruby
POST api/v1/models {:name => "New Model", :slug => "model-b"} # using the old history for model_a
ruby
PUT api/v1/models/models-c {:name => "New Model", :slug => "model-b"}
但是,由于模型的slug的唯一性存在冲突,我的实现不起作用。
我已尝试过以下
before_save -> { delete_old_slug_if_conflicts self.slug }
private
def delete_old_slug_if_conflicts (slug)
# get the id of the slug from the friendly_id_lug table
id = FriendlyId::Slug.where(slug: slug, sluggable_type: 'Model')[0].sluggable_id
# get an array of all the slugs for that model
slugs = FriendlyId::Slug.where(sluggable_id: id, sluggable_type: 'Model').order("created_at asc")
# if the count is more than 1, then the first one is the old history and is deleted,
if slugs.count > 1
id_to_del = slugs.first["id"].to_i
return FriendlyId::Slug.destroy(id_to_del) # remove the slug record to allow for saving
end
nil
end
有没有更好的方法来实现这种重新分配,还是有一些我不知道的东西?
顺便说一下,我不是铁杆专家,我使用Rails 4.2.5.1