undefined方法`method'for“String”:String

时间:2017-03-20 11:56:01

标签: ruby-on-rails ruby

我目前收到此错误:

  

未定义方法`street_address'表示“未设置”:字符串

我的目标是处理用户地址返回时发生的错误。

以下是发生错误的代码:

def address
    if params[formatted_address["address"]].nil?
      address = ''
      street_address = ''
      country = ''
      region = ''
      city = ''
      zip = ''
    else
      address = ActiveSupport::JSON.decode(formatted_address["address"])
      street_address = address["street_address"]
      country = address["country"]
      region = address["region"]
      city = address["locality"]
      zip = address["postal_code"]
    end   
  end

  info do
    {
      name: user_info.name,
      email: user_info.email,
      nickname: user_info.preferred_username,
      first_name: user_info.given_name,
      last_name: user_info.family_name,
      gender: user_info.gender,
      phone: user_info.phone_number,
      birthdate: user_info.birthdate,
      street_address: address.street_address, <-- error occurs here
      country: address.country,
      region: address.region,
      city: address.city,
      zip: address.zip,
      urls: { website: user_info.website }
    }
  end

2 个答案:

答案 0 :(得分:0)

在else语句中,我刚创建了一个副本JSON,其中包含我想要返回的值

def address
        if formatted_address["address"].nil?
          address = JSON.parse('{
            "street_address": "",
            "country": "",
            "region": "",
            "locality": "",
            "postal_code": ""
            }')
        else
          address = ActiveSupport::JSON.decode(formatted_address["address"])
        end
      end

  info do
    {
      name: user_info.name,
      email: user_info.email,
      nickname: user_info.preferred_username,
      first_name: user_info.given_name,
      last_name: user_info.family_name,
      gender: user_info.gender,
      phone: user_info.phone_number,
      birthdate: user_info.birthdate,
      street_address: address["street_address"],
      country: address["country"],
      region: address["region"],
      city: address["locality"],
      zip: address["postal_code"],
      urls: { website: user_info.website }
    }
  end

答案 1 :(得分:-1)

如果要在空白地址参数的情况下在地址字段中保存空格,则应在迁移/表格中将默认值设置为“”。