设置属性时遇到问题
我有一个项目 ActiveRecords
,我正在尝试使用块为每个项目设置默认值(“测试项目”)。
在此表达式中:
list = {"type1", "type2", "type3", "type4", "..."}
list.each { |name| @item.attributes["#{name}"] = "Test item"] }
未设置值。
我必须使用 @item.attributes["#{name}"] 进行插值,因为我无法对每个项目执行此操作:
@item.tipe1 = "Test item"
那么,第一个语句中会发生什么?为什么?如果我想做的事不可能以这种方式实现,我该如何做呢?
I have an item ActiveRecords
and I am trying to set a default value ("Test item") for each of them using a block.
In this expression:
list = {"type1", "type2", "type3", "type4", "..."}
list.each { |name| @item.attributes["#{name}"] = "Test item"] }
values aren't set.
I must use @item.attributes["#{name}"]
for interpolation because I can't do this for every item:
@item.tipe1 = "Test item"
So, what happens in the first statement? Why? If what I would like to do is not possible in that way, how I can do the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
赋值
@items.attributes["#{name}"] = "Test item"]
不起作用,因为attributes
方法每次返回一个新的 Hash 对象调用它。因此,您并没有像您想象的那样更改@items
' 对象的值。相反,您正在更改已返回的新哈希值。这个哈希值在每次迭代后都会丢失(当然,当each
块完成时)。一种可能的解决方案是使用
@items
' 属性的键创建一个新的哈希,并通过attributes=
方法分配它。The assignment
@items.attributes["#{name}"] = "Test item"]
does not work, because theattributes
method returns a new Hash object each time you call it. So you are not changing the value of the@items
' object as you thought. Instead you are changing the value of the new Hash that has been returned. And this Hash is lost after each iteration (and of course when theeach
block has finished).A possible solution would be to create a new Hash with the keys of the
@items
' attributes and assign this via theattributes=
method.您可以使用 send 方法来达到此目的。也许是这样的:
You can use the send method for this purpose. Perhaps like this:
我认为问题在于您只是更改返回的属性哈希,而不是 ActiveRecord 对象。
您需要执行类似的操作:
按照您的示例,也许类似:
顺便说一句,
"#{e}"
与字符串表达式e
或任何类型相同:e.to_s
。第二个例子,也许更容易阅读:使用
attributes=
方法可能适用于哈希常量,例如:对于完全生成的属性,您可以采用 DanneManne 的建议并使用发送。
I think the problem is that you are only changing the returned attribute hash, not the ActiveRecord object.
You need to do something like:
Following your example, perhaps something like:
BTW,
"#{e}"
is the same thing as String expressione
or for any type:e.to_s
. A second example, perhaps easier to read:Using the
attributes=
method is probably intended for hash constants, like:For entirely generated attributes you could take DanneManne's suggestion and use send.