-
15-10-2019 - |
题
我有一个物品 ActiveRecords
我正在尝试使用一个块为每个块设置默认值(“测试项目”)。
在这个表达中:
list = {"type1", "type2", "type3", "type4", "..."}
list.each { |name| @item.attributes["#{name}"] = "Test item"] }
值未设置。
我必须使用 @item.attributes["#{name}"]
用于插补,因为我不能为每个项目做到这一点:
@item.tipe1 = "Test item"
那么,第一个声明会发生什么?为什么?如果我想做的是不可能的,那么我如何做同样的事情?
解决方案
那作业 @items.attributes["#{name}"] = "Test item"]
不起作用,因为 attributes
方法每次调用时都会返回一个新的哈希对象。因此,您没有更改 @items
``按照您的想法。相反,您正在更改已返回的新哈希的价值。每次迭代后,这个哈希都会丢失(当然,当 each
块已经完成)。
一种可能的解决方案是用键创建一个新的哈希 @items
'属性并通过 attributes=
方法。
h = Hash.new
# this creates a new hash object based on @items.attributes
# with all values set to "Test Item"
@items.attributes.each { |key, value| h[key] = "Test Item" }
@items.attributes = h
其他提示
您可以为此目的使用发送方法。也许这样:
list = {"type1", "type2", "type3", "type4", "..."}
list.each { |name| @item.send("#{name}=", "Test item") }
我认为问题是您只是更改返回的属性哈希,而不是ActiverEcord对象。
您需要做类似的事情:
# make hash h
@items.attributes = h
按照您的示例,也许是类似的:
@items.attributes = %w{type1 type2 type3 type4}.inject({}) { |m, e| m[e] = 'Test item'; m }
顺便提一句, "#{e}"
与字符串表达式是同一件事 e
或任何类型: e.to_s
. 。第二个例子,也许更容易阅读:
a = %w{type1 type2 type3 type4}
h = {}
a.each { |name| h[name] = 'test item' }
@items.attributes = h
使用 attributes=
方法可能是针对哈希常数的,例如:
@items.attributes = { :field => 'value', :anotherfield => 'value' }
对于完全生成的属性,您可以采用 Dannemanne的 建议和使用发送。
不隶属于 StackOverflow