Rails验证仅在已发布时验证发布日期是否存在。
Rails验证仅在已发布时验证发布日期是否存在。
当用户决定发布一篇文章时,我想确保模型的发布日期被设置。
我有以下代码:
class Article < ApplicationRecord before_validation :check_published validates :publish_date, presence: true, if: :article_published? def check_published self.publish_date = Time.now if self.published end def article_published? self.published end end
在我的Article模型测试文件中:
require 'test_helper' class ArticleTest < ActiveSupport::TestCase def setup @new_article = { title: "Car Parks", description: "Build new car parks", published: true } end test "Article Model: newly created article with published true should have publish date" do article = Article.new(@new_article) puts "article title: #{article.title}" puts "article published: #{article.published}" puts "article publish date: #{article.publish_date}" assert article.publish_date != nil end end
测试失败了。
我所做的事情可能吗?还是我需要在控制器中完成?
问题出现的原因是在使用new
方法创建文章对象时,publish_date
的验证没有被触发。解决方法是使用create
方法创建文章对象,这样可以触发验证。
在这个问题中,article = Article.new(_article)
只是创建了一个文章对象,而没有将其保存到数据库中,所以publish_date
的验证没有被触发。可以尝试使用article = Article.create(_article)
来创建文章对象。
从这个问题中可以看出,new
方法不会触发任何验证。可以参考这个stackoverflow.com/questions/2472393#2472416上的回答了解关于new vs create
的讨论。
(完)