我正在为after_create回调上的帖子创建一个插件,如果该插件已经存在,我不确定如何在末尾附加一个数字。
class Post < ActiveRecord::Base
attr_accessible :body, :title, :slug
after_create :create_slug
validates_uniqueness_of :slug
def create_slug
existing = Post.where("slug LIKE ?", "#{title.parameterize}%").length
existing > 0 ? slug = "#{title.parameterize}-#{existing+1}" : slug = title.parameterize
self.update_attributes(slug: slug)
end
end例如,这不起作用,因为我的where子句匹配标题为"Some title That is Different“的帖子。
一种解决方案是附加post.id,而不是尝试枚举。在帖子被删除的情况下,这也可能更好。但我不希望删除任何帖子,而且不使用I似乎更有意义。
有什么建议吗?
发布于 2013-04-10 06:31:56
将会
Post.where(title: title).count在你的情况下给你正确的号码?
在DB中的slug列上设置唯一约束也很重要,因为如果在相似的时间创建具有相同标题的两个帖子,则此算法会受到竞争条件的影响。Rails本身不能保证列的唯一性。
https://stackoverflow.com/questions/15913606
复制相似问题