我有一个has_many接受嵌套属性的关联.我需要在集合中至少有一个关联对象,所以我写了一个自定义验证器:
class MinimumCollectionSizeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if value.size < options[:size]
record.errors[attribute] << (options[:message] || "must have at least #{options[:size]} line.")
end
end
end
Run Code Online (Sandbox Code Playgroud)
该模型看起来像:
has_many :foos, :dependent=>:destroy
accepts_nested_attributes_for :foos
validates :foos, :minimum_collection_size=>{:size=>1}
Run Code Online (Sandbox Code Playgroud)
这在模型创建方面效果很好,但在更新时失败了. @my_model.update_attributes(params[:my_model])即使所有foos都被_destroy删除,也会返回true.
我怎么update_attributes能表现得一样save?
我有一张有很多照片的专辑.counter_cache设置会更新相册表中的photos_count列.如何限制相册的照片数量?
如何才能使提交产品至少需要两个选项记录?
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
Run Code Online (Sandbox Code Playgroud) 我有一个活动模型.每个活动可以有多个会话.
我想确保没有模型可以存在,如果没有至少1个与之关联的会话.
validates :sessions, :length => { :minimum => 1 }
Run Code Online (Sandbox Code Playgroud)
问题是 - 当我尝试通过调用我的模型方法来创建特定事件的会话时:
create_sessions()
Run Code Online (Sandbox Code Playgroud)
这有点像:
sessions.create(event_id: id,date: x,day_of_the_week:x.strftime("%A"),classPin: pin)
Run Code Online (Sandbox Code Playgroud)
对于事件将运行的每个日期.
它无法保存错误:
ActiveRecord::RecordNotSaved in EventsController#create
You cannot call create unless the parent is saved
Run Code Online (Sandbox Code Playgroud)
当然 - 到目前为止还没有保存新的事件记录 - 因此,由于在保存父项之前创建一个不可用的关联,因此无法创建此关联!
因此,这种关系之间的任何验证如何工作 - 因为验证发生在保存时间......但我想在保存事件之前验证会话数将大于0!