1
我目前爲我的模型動態生成url slugs(並實現to_param/self.from_param來解釋它們)。我的slu generation代代碼感覺冗長,可以使用重構。重構:爲模型生成一個獨特的slu 012
你會如何重構這個,使它仍然可讀,但不那麼冗長,也許更清楚?
關係
用戶的has_many:列出
列表 belongs_to的:所有者
代碼
def generate_slug
if self.owner
slug_found = false
count = 0
temp_slug = to_slug
until slug_found
# increment the count
count += 1
# create a potential slug
temp_slug = if count > 1
suffix = "_" + count.to_s
to_slug + suffix
else
to_slug
end
# fetch an existing slug for this list's owner's lists
# (i.e. owner has many lists and list slugs should be unique per owner)
existing = self.owner.lists.from_param(temp_slug)
# if it doesn't exist, or it exists but is the current list, slug found!
if existing.nil? or (existing == self)
slug_found = true
end
end
# set the slug
self.slug = temp_slug
else
Rails.logger.debug "List (id: #{self.id}, slug: #{self.slug}) doesn't have an owner set!"
end
end
剛剛獲得最後一個存在的問題是,如果刪除了一個(因爲內容可由用戶基礎刪除),則存在差距。在我看來,如果有人創建了第一個,使用相同的名稱(因此將_2附加到slug),但是隨後刪除了第一個,現在沒有後綴的slug不可用。 –
我不認爲這是不好的差距。也許你可以依靠其他參數來確定它是最後一個參數。 – oldergod
你可能會建議什麼? –