ruby-on-rails - 通过循环一次设置多个模型属性
问题描述
在保存用户之前,我使用虚拟属性来连接并形成地址。因此,当他们单击编辑用户时,我想再次填充表单中的字段。每次我尝试分配它们时,它们都会返回零?
这就是我从设计注册控制器 before_action 编辑中调用的内容:
def test
resource.populate_address_attributes
end
这是我尝试使用的方法:
def populate_address_attributes
if address == nil || address == ""
return false
else
attributes = address.split(",")
[self.number, self.street_name, self.area, self.postcode, self.state].each { |x| x = attributes.delete_at[0]}
end
end
我得到的是:
=> [nil, nil, nil, nil, nil]
也许我想让它变得复杂?
解决方案
当您传递[self.number, self.street_name]
etc 时,您传递的是这些属性的值(它们是 nil 并且因此是不可变的)。
试试这个
def populate_address_attributes
if address == nil || address == ""
return false
else
attributes = address.split(",")
[:number, :street_name, :area, :postcode, :state].each_with_index do |field, index|
self.public_send("#{field}=", attributes[index])
end
end
end
推荐阅读
- python - Python 自省:mro() 方法在哪里?
- c# - 按钮未将变量传递给控制器
- javascript - 如何删除重复项并计算两个数组之间的差异?
- .net - Visual Studio 2017 中的 Nuget 包错误
- sql-server - 将列值分配给 mssql 中的变量
- javascript - 在 IE10 崩溃中,访问 dom 元素时出现“无法评估表达式”错误
- python - 在 Python 中压缩 zip 文件时数据意外结束
- ruby - 我可以以惯用/简洁的方式使这种“块包装”成为可选吗?
- macos - 如何在 OS 10.13.6 上创建文件以同时打开多个不同的 Chrome 浏览器网站
- javascript - 如何修复onclick“未定义”