Ruby on rails 验证ActiveRecord中的关联模型(已通过)
我希望能够创建和编辑模型以及相关的多对多实体。 相关对象应通过具有附加字段和完整性验证(例如唯一性或存在性)的模型连接。 我想用Rails提供的标准验证机制检查完整性 例如,一个Ruby on rails 验证ActiveRecord中的关联模型(已通过),ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我希望能够创建和编辑模型以及相关的多对多实体。 相关对象应通过具有附加字段和完整性验证(例如唯一性或存在性)的模型连接。 我想用Rails提供的标准验证机制检查完整性 例如,一个Post(如Stackoverflow上的这里),至少有一个标签,但不超过3个标签标记不能多次分配给单个Post。 此外,标记将被排序(优先级在联接表中) 模型应使用带有验证的自定义验证器,并在违反任何约束的情况下向发布错误添加错误消息。 编辑时,如果任何验证失败(例如,删除了文章标题或添加了太多标记),则不会保存模型及
Post
(如Stackoverflow上的这里),至少有一个标签
,但不超过3个标签
<代码>标记不能多次分配给单个Post
。
此外,标记将被排序(优先级
在联接表中)
模型应使用带有验证
的自定义验证器,并在违反任何约束的情况下向发布错误
添加错误消息。
编辑时,如果任何验证失败(例如,删除了文章标题或添加了太多标记),则不会保存模型及其与标记的关系(标记分配
)
示例模型:
class Post < ActiveRecord::Base
has_many :tag_assignments
has_many :tags, :through => :tag_assignments
validates :title,
presence: true
validates :content,
presence: true
validates :number_of_tags
def number_of_tags
valid = self.tags.count.in? 1..3
errors.add('error: 1 <= tag.size <= 3') unless valid
valid
end
end
class Tag < ActiveRecord::Base
has_many :tag_assignments
has_many :posts, through: :tag_assignment
validates :name,
presence: true
end
class TagAssignment < ActiveRecord::Base
belongs_to :user
belongs_to :tag
validates :tag_id,
uniqueness: {scope: :post_id}
validates :priority,
presence: true,
uniqueness: {scope: :tag_id}
end
class Post:标记\u分配
验证:标题,
存在:真实
验证:内容,
存在:真实
验证:标记的数量
def标签的数量
valid=self.tags.count.in?1..3
错误。添加('error:1我需要的解决方案是使用.build
而不是参考这个答案。我想这就是你需要的。
post = Post.build(title: 'title', content: 'content')
post.save # false
post.errors # contains message: 'error: 1 <= tag.size <= 3'
post.tagger << Tag.first
post.save # true
post_id = post.id
post = Post.find(post_id)
post.tagger << Tag.all[5..10]
post.save # false
# but tag_assignments were already created
# and old TagAssignments were not destroyed
post = Post.build(title: 'title', content: 'content')
post.tag_assignments.build(tag: Tag.first, priority: 1)
post.save # true, TagAssignments are persisted here
post_id = post.id
post.tag_assignments = [TagAssignment.new(tag: Tag.first, priority: 1)] # an update on assignments sets user_id = NULL and new assignment is inserted
post.title = nil
post.valid? # false, but correct TagAssignments were replaced with new ones