【发布时间】:2023-03-23 06:55:01
【问题描述】:
我正在尝试使用条件解决关联对象的验证问题。
用户在成为作者之前无需填写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 模型添加第二个验证,但这不是 DRY。有没有更好的解决方案?
【问题讨论】:
标签: ruby-on-rails validation associations