我有一个ruby函数,如果找不到标题,它将创建一个话题主题。
def get_topic(user,title,created_at,bumped_at,last_posted_at,excerpt)
title = title.gsub(/ /,' ')
puts "get_topic.title:'#{title}' user.id:#{user.id} created_at:#{created_at} last_posted_at:#{last_posted_at} excerpt:#{excerpt}"
result = Topic.find_by_title(title)
if result == nil then
result = Topic.create
result.title = title
result.fancy_title = title
result.user_id = user.id
result.last_post_user_id = user.id
result.updated_at = last_posted_at
result.created_at = created_at
result.bumped_at = bumped_at
result.last_posted_at = last_posted_at
result.excerpt = excerpt
result.save!
else
puts result
puts created_at,bumped_at,last_posted_at
if result.user_id != user.id then
result.user_id = user.id
result.last_post_user_id = user.id
end
if result.updated_at != last_posted_at then
result.updated_at = last_posted_at
end
if result.created_at != created_at then
result.created_at = created_at
end
if result.bumped_at != bumped_at then
result.bumped_at = bumped_at
end
if result.last_posted_at != last_posted_at then
result.last_posted_at = last_posted_at
end
if result.excerpt != excerpt then
result.excerpt = excerpt
end
if result.changed.length > 0 then
result.save!
puts result.slug
post = result.first_post
post.created_at = created_at
post.updated_at = result.updated_at
post.baked_at = result.bumped_at
post.last_version_at = result.last_posted_at
post.user_id = result.user_id
post.last_editor_id = result.user_id
post.raw = result.excerpt
post.save!
puts post
#puts user.id
end
end
puts "get_topic.result.slug:#{result.slug}"
return result
end
在代码创建主题之前,它会搜索标题。 title = title.gsub(/ /,'')结果= Topic.find_by_title(title) 如果结果为零,则会创建一个主题。
它适用于大多数主题,但是,对于一个标题,它会抛出ActiveRecord :: RecordInvalid:验证失败:保存主题时,标题已经被使用。
topic.title的价位设置为
validates :title, if: Proc.new { |t| t.new_record? || t.title_changed? },
presence: true,
topic_title_length: true,
censored_words: true,
quality_title: { unless: :private_message? },
max_emojis: true,
unique_among: { unless: Proc.new { |t| (SiteSetting.allow_duplicate_topic_titles? || t.private_message?) },
message: :has_already_been_used,
allow_blank: true,
case_sensitive: false,
collection: Proc.new { Topic.listable_topics } }
我已使用Topic.find_by_title('title')在控制台中签入。标题不存在主题。我使用Topic.find_by_sql(“从标题为“ title %%”之类的标题中选择*)进行检查。
还可以进行其他哪些检查……当找不到与该标题相关的主题时,该主题标题已被使用的错误会导致什么?
更多信息
我尝试打开允许重复的标题。代码运行正常,没有错误,但是导入后没有引起标题错误的标题。感觉错误消息是错误的。