2
我試圖解決與條件關聯對象的驗證。驗證關聯對象(延遲驗證)
直到他是作者爲止,用戶不需要填寫author_bio
。因此,應用程序需要確保,如果用戶已經創建了任何帖子,那麼作者無法創建帖子,如果沒有author_bio
和author_bio
無法刪除。
class User < ApplicationRecord
has_many :posts, foreign_key: 'author_id', inverse_of: :author
validates :author_bio, presence: { if: :author? }
def author?
posts.any?
end
end
class Post < ApplicationRecord
belongs_to :author, class_name: 'User', inverse_of: :posts, required: true
end
不幸的是,這並不在創造新的崗位驗證作者:
user = User.first
user.author_bio
=> nil
post = Post.new(author: user)
post.valid?
=> true
post.save
=> true
post.save
=> false
post.valid?
=> false
那麼,怎樣才能防止我不author_bio
創造的新職位由用戶?我可以在Post
模型中添加第二個驗證,但這不是乾的。有沒有更好的解決方案?