0
我想確保在用戶決定發佈文章時爲發佈日期設置發佈日期。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
在我的文章模型測試文件:
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()不會運行任何模型驗證。我在印象之下new()和create()運行驗證。 – Zhang
沒錯。 'new'不運行任何驗證。你可以檢查這個SO回答https://stackoverflow.com/questions/2472393/rails-new-vs-create#2472416關於'新vs創建'主題。 –