访问每个循环中的哈希值

时间:2017-07-13 09:29:24

标签: ruby-on-rails

我正在开发一个为用户创建共享链接的Rails API。输入接受如下所示的JSON哈希:

{
    "shared_with":{
        "1": "someemail@example.com",
        "2": "anotheremail@example.com"
    },
    "expiry": "30 June 2017"
}

当它到达控制器时,它会遍历已提交的电子邮件,创建数据库条目,并为每个电子邮件触发邮件程序。这是控制器动作:

def create
  @user = current_user
  @recipients = share_params

  # save and mail in one step

  # first iterate over the email addresses sent
  @recipients[:shared_with].each do |recipient|

    # assign a token
    @token = Share.generate_token

    # save record, token, expiry
    @user.shares.create!(
      token: @token,
      shared_with: **???**,
      expiry: @recipients[:expiry]
    )

    # trigger mailer for email
    ShareMailer
      .share_dealsheet(recipient, @user, @token)
      .deliver_now
  end

  json_response(:created)
end

所有内容都正确保存并且正在生成邮件程序,但我无法弄清楚要放入shared_with:以获取当前电子邮件的内容。

1 个答案:

答案 0 :(得分:1)

你的json中有错误(缺少逗号)。

{
    "shared_with":{
        "1": "someemail@example.com",
        "2": "anotheremail@example.com"
    },
    "expiry": "30 June 2017"
}

现在将您的代码更改为:

@recipients[:shared_with].each do |key,recipient|

    # assign a token
    @token = Share.generate_token

    # save record, token, expiry
    @user.shares.create!(
      token: @token,
      shared_with: recipient,
      expiry: @recipients[:expiry]
    )

    # trigger mailer for email
    ShareMailer
      .share_dealsheet(recipient, @user, @token)
      .deliver_now
  end