Mar*_*ser 22 activerecord ruby-on-rails
我有一个看起来像这样的验证:
class Book < ActiveRecord::Base
belongs_to :author
validates :name, uniqueness: { scope: :author_id }
end
Run Code Online (Sandbox Code Playgroud)
问题是我想允许作者id为nil的重复名称.有没有办法使用validates方法(而不是自定义验证)?
dee*_*our 26
是的,有Proc和:unless上验证.
class Book < ActiveRecord::Base
belongs_to :author
validates :name, uniqueness: { scope: :author_id }, unless: Proc.new { |b| b.author_id.blank? }
end
Run Code Online (Sandbox Code Playgroud)
推荐阅读: http ://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless
Make it conditional:
validates :name, uniqueness: { scope: :author_id }, if: :author_id?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4425 次 |
| 最近记录: |