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
模型中添加第二个验证,但这不是干的。有没有更好的解决方案?