gpt4 book ai didi

ruby-on-rails - 如何在 ruby​​ 循环中动态访问模型属性?

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:14 25 4
gpt4 key购买 nike

我的模型类:

class item
attr_accessor :item_name
attr_accessor :item_url
attr_accessor :item_label
.
.
end

当我想为这个属性赋值时。不是一个一个赋值,即item.item_name="abc"

我想用硬编码名称将所有属性放入循环中,并从其他来源分配。

['item_url','item_url','item_label'].each do |attr|
item.attr=values from some other source #error on this line
#or
item."#{attr}"=values from some other source #error on this line
end

他们两个都不工作。欢迎任何建议

最佳答案

你可以这样做:

 item.send((attr + "="), values from some other source)

或:

hash = {}
['item_url','item_url','item_label'].each do |attr|
hash[attr] = value
end
item.attributes = hash

关于ruby-on-rails - 如何在 ruby​​ 循环中动态访问模型属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com