【发布时间】:2014-11-13 16:10:09
【问题描述】:
我有模型:
class Agency < ActiveRecord::Base
SPECIALIZATIONS_LIMIT = 5
has_many :specializations
has_many :cruise_lines, through: :specializations
validate :validate_specializations_limit
protected
def validate_specializations_limit
errors.add(:base, "Agency specializations limit is #{SPECIALIZATIONS_LIMIT}.") if specializations.count > SPECIALIZATIONS_LIMIT
end
end
class CruiseLine < ActiveRecord::Base
has_many :specializations
has_many :agencies, through: :specializations
end
class Specialization < ActiveRecord::Base
belongs_to :agency, inverse_of: :specializations
belongs_to :cruise_line, inverse_of: :specializations
end
在我的服务中,我尝试像这样保存代理和专业化关系:
attributes = params.require(:agency).permit(
:name, :website, :description, :booking_email, :booking_phone,
:optional_booking_phone, :working_hours, :cruise_line_ids => []
)
agency.update_attributes(attributes)
attributes[:cruise_line_ids].select{|x| x.to_i > 0}.each do |cruise_line_id|
agency.specializations.build(cruise_line_id: cruise_line_id)
end
这段代码的工作原理:
1) 更新属性;
2) 如果我取消选中一些带有巡航线路的复选框,它会保存关系并更新它们;
3)如果我输入错误的数据或选择过多的游轮复选框,它不会保存数据,但也不会显示错误!
如果我在构建关系的块之后立即添加一些检查代码puts agency.errors.inspect - 它完全按照我的预期工作:如果所有内容都保存 - 显示成功消息,如果发生验证错误 - 显示错误消息。
问题:
为什么在保存代码后立即添加puts agency.errors.inspect 会使一切按预期工作?
【问题讨论】:
标签: ruby-on-rails validation activerecord model