ruby-on-rails - 防止在其他页面输入相同的链接
问题描述
在我的网站上,当您创建产品页面时,您可以上传文件或添加链接。为了防止在同一个产品页面中输入相同的链接,有这个
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
解决方案
您可以设置allow_nil: true
为uniqueness: true
, 并去除url
之前的验证以防止空白 url。
推荐阅读
- python - LSTM 层不接受 CNN 层输出的输入形状
- javascript - 如何使用nodemailer将图像附件作为base64发送?
- php - 自动构建 laravel 分页对象
- javascript - 如何为函数参数分配提示值
- python - #Pandas,根据另一列的标题名称(列名)向列添加值
- typescript - 使接口可选?
- google-apps-script - 如何使用 OnSubmit 触发器在谷歌电子表格上运行函数?
- php - 如何将 php 变量显示为 html?
- sql - 未在 GROUP BY 原因或聚合函数中选择的列?
- php - Google oauth 2.0 - 我需要刷新令牌吗?