首页 > 解决方案 > 防止在其他页面输入相同的链接

问题描述

在我的网站上,当您创建产品页面时,您可以上传文件或添加链接。为了防止在同一个产品页面中输入相同的链接,有这个

validate :check_download_links_unique!

    def check_download_links_unique!
      urls = download_links.reject(&:marked_for_destruction?).map!(&:url).compact.to_a
      errors.add(
        :download_links, :links_repetition
      ) if urls.uniq.length != urls.length
    end

现在我还想检查另一件事。我想防止进入另一个产品页面中已经添加的相同链接

我试图像这样添加模型/download_link.rb

validates :url, uniqueness: true

但它也阻止了文件的上传。有小费吗?

模型

# == Schema Information
#
# Table name: download_links
#
#  id                :integer          not null, primary key
#  url               :string
#  broken            :boolean          default(FALSE), not null
#  book_id           :integer
#  file_file_name    :string
#  file_content_type :string

# == Schema Information
#
# Table name: books
#
#  id               :integer          not null, primary key
#  title            :string           not null
#  slug             :string           not null
#  description      :text             not null
#  user_id          :integer
#  downloads_count  :integer          default(0), not null

标签: ruby-on-rails

解决方案


您可以设置allow_nil: trueuniqueness: true, 并去除url之前的验证以防止空白 url。


推荐阅读