通过循环一次设置多个模型属性

时间:2018-10-22 10:40:25

标签: ruby-on-rails ruby

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

这是我从设备注册控制器调用的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]

也许我正试图使其复杂化?

1 个答案:

答案 0 :(得分:1)

传递[self.number, self.street_name]等时,传递的是这些属性的值(它们为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