attributes也会始终返回true

attributes也会始终返回true

本文介绍了即使nested_attributes无效,update_attributes也会始终返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个带有嵌套数据的模型:

I have 2 models with nested data:

class Goodtender

  include Mongoid::Document
  include Mongoid::Timestamps

  field :name
  field :count
  references_many(:offerprices, :autosave => true)
  accepts_nested_attributes_for :offerprices, :allow_destroy => true, :reject_if => :all_blank

  validates_presence_of :name, :message => "Invalid"
  validates_numericality_of :count, :message => 'Invalid'
  validates_associated :offerprices, :message => 'Invalid'


end

class Offerprice

  include Mongoid::Document
  include Mongoid::Timestamps

  field :summ
  field :date_delivery, :type => DateTime
  field :note

  referenced_in :goodtender, :class_name => 'Goodtender'

  validates_presence_of :date_delivery, :message => "Invalid"
  validates_numericality_of :summ, :message => 'Invalid'

end

制作嵌套记录时,会进行正确的验证,例如,如果嵌套模型中的数据不正确,请执行以下命令:

When making nested records, correct validation takes place, for example, if data in nested model do not correct, so command:

@tender = Tender.new(params[:tender])
@tender.save

返回假

但如果更新数据:

@tender = Tender.find(params[:id])
@tender.update_attributes(params[:tender])

总是正确的

即使嵌套数据无效.在此,父项的数据更新和有效,如果父项的数据无效,则返回false,如果其中一个嵌套记录无效,保存时将忽略它们,并且update_attributes返回true.在更新所有嵌套数据链时是否有机会检查数据的有效性?谢谢您的回复.

Even if nested data do not valid. Here parent's data updates and valids and if parents' data does not valid returns false, if one of the nested record does not valid,they are ignored when you are saving and update_attributes returns true. Is there the opportunity to check data on validity in the time of updating all the nested data chain? Thank you for your respond.

我正在使用:Ruby 1.8.7RoR 3.0.9Mongoid 2.0.1

I'm using:Ruby 1.8.7RoR 3.0.9Mongoid 2.0.1

推荐答案

请检查每个模型的有效"功能以进行验证.请在您的代码中添加以下代码:

Please check "valid" function to each model for validate.Please add code as per below in your code :

@tender = Tender.find(params[:id]) <br/>
@tender.fieldname=params[:name] <br/>
if @tender.valid?  <br/>
   @tender.save <br/>
 end  <br/>

这篇关于即使nested_attributes无效,update_attributes也会始终返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:34