gpt4 book ai didi

ruby-on-rails - Rails 嵌套属性 : require at least two records

转载 作者:行者123 更新时间:2023-12-04 02:39:14 24 4
gpt4 key购买 nike

我怎样才能做到至少需要两个选项记录才能提交产品?

class Product < ActiveRecord::Base
belongs_to :user
has_many :options, :dependent => :destroy
accepts_nested_attributes_for :options, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
validates_presence_of :user_id, :created_at
validates :description, :presence => true, :length => {:minimum => 0, :maximum => 500}
end

class Option < ActiveRecord::Base
belongs_to :product
validates :name, :length => {:minimum => 0, :maximum => 60}
end

最佳答案

class Product < ActiveRecord::Base
#... all your other stuff
validate :require_two_options

private
def require_two_options
errors.add(:base, "You must provide at least two options") if options.size < 2
end
end

关于ruby-on-rails - Rails 嵌套属性 : require at least two records,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4309354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com