首页 > 解决方案 > 通过循环一次设置多个模型属性

问题描述

在保存用户之前,我使用虚拟属性来连接并形成地址。因此,当他们单击编辑用户时,我想再次填充表单中的字段。每次我尝试分配它们时,它们都会返回零?

这就是我从设计注册控制器 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]

也许我想让它变得复杂?

标签: ruby-on-railsruby

解决方案


当您传递[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

推荐阅读