首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >即使nested_attributes无效,update_attributes也始终返回true

即使nested_attributes无效,update_attributes也始终返回true
EN

Stack Overflow用户
提问于 2011-11-08 13:02:01
回答 1查看 871关注 0票数 4

我有两个嵌套数据的模型:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
@tender = Tender.new(params[:tender])
@tender.save

返回false

但是如果更新数据:

代码语言:javascript
复制
@tender = Tender.find(params[:id])
@tender.update_attributes(params[:tender])

总是返回true

即使嵌套的数据无效。在这里,父对象的数据更新并验证,如果父对象的数据无效,则返回false;如果其中一个嵌套记录无效,则在保存时忽略这些记录,并且update_attributes返回true。在更新所有嵌套的数据链时,是否有机会检查数据的有效性?感谢您的回复。

我使用的是:Ruby1.8.7Mongoid3.0.9 RoR 2.0.1

EN

回答 1

Stack Overflow用户

发布于 2012-07-07 12:46:05

请勾选每个模型的“有效”函数进行验证。请在您的代码中添加如下代码:

代码语言:javascript
复制
@tender = Tender.find(params[:id]) <br/>
@tender.fieldname=params[:name] <br/>
if @tender.valid?  <br/>
   @tender.save <br/>
 end  <br/>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8046143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档