Ruby-on-rails Rails 3 - 在更新前检查对象是否对参数有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10727498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:26:15  来源:igfitidea点击:

Rails 3 - check that object is valid with params before update

ruby-on-railsrubyruby-on-rails-3validation

提问by ExiRe

I have very newbie question. How can i check that object of model is valid with new params BEFORE updating it?

我有一个非常新手的问题。在更新模型之前,如何使用新参数检查模型对象是否有效?

I want transform that:

我想转换:

def update
  @obj = SomeModel.find( params[:id] )

  if @obj.update_attributes( params[:obj] )
    # That have been updated
  else
    # Ups, errors!
  end
end

To something like that:

对于这样的事情:

def update
  @obj = SomeModel.find( params[:id] )

  if @obj.valid_with_new_params( params[:obj] )
    @obj.update_attributes( params[:obj] )
  else
    # Ups, errors!
  end
end

回答by Justin

To update the attributes without saving them, you can use

要更新属性而不保存它们,您可以使用

@obj.assign_attributes( params[:obj] )

Then to check if the object is valid, you can call

然后检查对象是否有效,您可以调用

@obj.valid?

If the object is notvalid, you can see the errors (only after calling .valid?) by calling

如果对象是不是有效的,你可以看到错误(只打完电话后.valid?拨打)

@obj.errors

If the object isvalid, you can save it by calling

如果对象有效的,你可以通过调用保存

@obj.save

However, all of this usuallyisn't necessary. If the object isn't valid, then ActiveRecord won't save the object to the database, so all of the attribute changes are forgotten when you leave the controller action.

但是,所有这些通常都不是必需的。如果对象无效,则 ActiveRecord 不会将该对象保存到数据库中,因此当您离开控制器操作时,所有属性更改都会被忘记。

Also, since an invalid record won't be saved to the database, you can always just call Object.find() again to get the original object back.

此外,由于无效记录不会保存到数据库中,因此您始终可以再次调用 Object.find() 以取回原始对象。

回答by Frederick Cheung

You can call the valid?method to run the validations.

您可以调用该valid?方法来运行验证。

This doesn't guarantee that a subsequent save will succeed if some of your validations depend on the state of other objects in the database. Te save could also fail for reasons unconnected to validations (eg a foreign key constraint)

如果您的某些验证依赖于数据库中其他对象的状态,这并不能保证后续保存会成功。由于与验证无关的原因(例如外键约束),保存也可能失败

I'm not sure why you'd want this pattern

我不知道你为什么想要这个模式

回答by Femaref

The object won't be saved if the passed argument doesn't produce a valid object, so you can use your way just fine. You can see the errors (if any) using the @obj.errorsarray.

如果传递的参数没有产生有效的对象,则该对象将不会被保存,因此您可以很好地使用您的方式。您可以使用@obj.errors数组查看错误(如果有)。

回答by Flexoid

update_attributesmethod validate object and return false if object is invalid. So, you can just write:

update_attributes方法验证对象,如果对象无效则返回 false。所以,你可以写:

if @obj.update_attributes( params[:obj] )
  # That have been update
else
  # Ups, errors!
end

回答by Gerry

The answer is that you can define a method

答案是你可以定义一个方法

def valid_with_new_params(hash)
   self.attributes = hash
   valid?
end

But that would be unnecessary because @obj.update_attributes(params[:obj])returns trueif the obj was successfully updated and falseotherwise. Note also that internally the update_attributesmethod runs all validations on the @objso that you have @obj.errorsavailable if the update failed.

但这将是不必要的,因为如果 obj 成功更新,则@obj.update_attributes(params[:obj])返回truefalse否则返回。另请注意,该update_attributes方法在内部运行所有验证,@obj以便您@obj.errors在更新失败时可用。

回答by Beena Shetty

To update the attributes without saving them

更新属性而不保存它们

@obj.attributes = params[:obj]   0r
@obj.attributes = {:name => “Rob”}

To then check if the object is valid

然后检查对象是否有效

@obj.valid?

To check if there is any error

检查是否有任何错误

@obj.errors