【问题标题】:How can you force validation of all fields of nested models, even if they have not changed? (Rails 3.1)如何强制验证嵌套模型的所有字段,即使它们没有更改? (轨道 3.1)
【发布时间】:2011-09-21 16:05:55
【问题描述】:

当您使用包含嵌套模型属性的表单编辑模型时,似乎只有在子对象上的至少一个字段发生更改时才验证子对象。

但是,假设您的验证规则已更改,因此正在编辑的一个或多个嵌套模型不再被视为有效。如何强制 Rails 重新验证所有嵌套模型的所有字段?

更新

这是一个完全有效的技巧。我希望有人知道更优雅的方法。

# parent.rb

has_many :children

# Manually force validation of all the children.
# This is lame because if you have multiple child associations, you'll have to 
# keep updating this method.
def reset_validation
   self.children.each{|child| child.valid? }
   self.valid?
end

# parent_controller.rb
def update
  @parent.reset_validation

  if @parent.update_attributes(params[:parent])
    redirect_to(root_path, :notice => 'Parent successfully updated.')
  else
   render :action => "edit"
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    这个问题的答案很简单。在父模型上,您只需明确声明要验证关联的子模型。

    # parent.rb
    validates_associated :children
    

    【讨论】:

    • 嗨@cailinanne!我已经以同样的方式临时解决了这个问题,但是验证抛出的错误消息只是 italic Children is invalid italic 所以它不会显示每个验证错误信息。您是否以某种方式解决了这个问题?提前致谢!阿尔贝托
    • @albertopriore 您是否按字面意思使用“儿童”?它需要是 validates_associated :association_name。因此,例如,如果您“have_many: users”,您将“validates_associated :users”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    相关资源
    最近更新 更多