update_attributes returns always true, even if nested_attributes are not valid

时光怂恿深爱的人放手 提交于 2019-12-21 20:06:56

问题


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

returns false

but if update data:

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

always eturns 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.

I'm using: Ruby 1.8.7 RoR 3.0.9 Mongoid 2.0.1


回答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/>


来源:https://stackoverflow.com/questions/8046143/update-attributes-returns-always-true-even-if-nested-attributes-are-not-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!