Ruby-on-rails 在一行中更改多个对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9751423/
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:03:57  来源:igfitidea点击:

Change multiple object attributes in a single line

ruby-on-railsruby-on-rails-3

提问by jay

I was wondering, when you create an object you can often set multiple attributes in a single line eg:

我想知道,当您创建一个对象时,您通常可以在一行中设置多个属性,例如:

 @object = Model.new(:attr1=>"asdf", :attr2 => 13, :attr3 => "asdfasdfasfd")

What if I want to use find_or_create_by first, and then change other attributes later? Typically, I would have to use multiple lines eg: @object = Model.find_or_create_by_attr1_and_attr2("asdf", 13) @object.attr3 = "asdfasdf" @object.attr4 = "asdf"

如果我想先使用 find_or_create_by,然后再更改其他属性怎么办?通常,我必须使用多行,例如:@object = Model.find_or_create_by_attr1_and_attr2("asdf", 13) @object.attr3 = "asdfasdf" @object.attr4 = "asdf"

Is there some way to set attributes using a hash similar to how the Model.new method accepts key-value pairs? I'm interested in this because I would be able to set multiple attributes on a single line like:

是否有某种方法可以使用类似于 Model.new 方法接受键值对的方式使用哈希设置属性?我对此很感兴趣,因为我可以在一行上设置多个属性,例如:

 @object = Model.find_or_create_by_attr1_and_attr2("asdf", 13)
 @object.some_method(:attr3 => "asdfasdf", :attr4 => "asdfasdf")

If anyone has any ideas, that would be great!

如果有人有任何想法,那就太好了!

回答by rjz

You want to use assign_attributesor update(which is an alias for the deprecated update_attributes):

您想使用assign_attributesor update(这是 deprecated 的别名update_attributes):

@object.assign_attributes(:attr3 => "asdfasdf", :attr4 => "asdfasdf")

@object.update(attr3: "asdfasdf", attr4: "asdfasdf")

If you choose to updateinstead, the object will be saved immediately (pending any validations, of course).

如果您选择update改为,对象将立即保存(当然,等待任何验证)。

回答by Veraticus

The methods you're looking for are called assign_attributesor update_attributes.

您正在寻找的方法称为assign_attributesor update_attributes

@object.assign_attributes(:attr3 => "asdfasdf", :attr4 => "asdfasf") # @object now has attr3 and attr4 set.
@object.update_attributes(:attr3 => "asdfasdf", :attr4 => "asdfasf") # @object now has attr3 and attr4 set and committed to the database.

There are some security concerns with using these methods in Rails applications. If you're going to use either one, especially in a controller, be sure to check out the documentation on attr_accessibleso that malicious users can't pass arbitrary information into model fields you would prefer didn't become mass assignable.

在 Rails 应用程序中使用这些方法存在一些安全问题。如果您打算使用任何一种,尤其是在控制器中,请务必查看attr_accessible上的文档,以便恶意用户无法将任意信息传递到您不希望成为可批量分配的模型字段中。