【问题标题】:How to properly pass parameter in query string with redirect_to? (Rails 4)如何使用 redirect_to 在查询字符串中正确传递参数? (导轨 4)
【发布时间】:2015-05-10 00:50:05
【问题描述】:

我正在使用 rails 4 构建一个联系表单创建应用程序。

用户可以创建联系人表单(在应用程序中称为Contactable),提交时会创建一个Contact 并将联系人重定向到用户指定的 URL。

我正在尝试通过重定向将联系人的电子邮件地址作为查询字符串传递。

使用我当前的设置,电子邮件确实在查询字符串中传递,但它丢失了“@”符号。

如果联系表单与示例电子邮件(如 john@website.com)一起提交,则查询字符串的构建方式如下...

http://website.com/?email=johnwebsite.com

如您所见,它丢失了“@”字符。我怎样才能保留那个 @ 字符?

在联系人控制器的创建函数中,这是我构建查询字符串的方式...

respond_to do |format|
  if @contact.save
    if @contactable.redirect_url.present?
      format.html { redirect_to @contactable.redirect_url + '?email=' + @contact.email }
      format.json { render :show, status: :created, location: @contact }
    else
      format.html { redirect_to :back, notice: @contactable.thanks_message }
      format.json { render :show, status: :created, location: @contactable }
    end
  else
    format.html { render :new }
    format.json { render json: @contact.errors, status: :unprocessable_entity }
  end
end

感谢您的任何意见!

【问题讨论】:

  • 请显示config/routes.rb文件。

标签: ruby-on-rails ruby url-redirection url-parameters query-parameters


【解决方案1】:

您不应该通过字符串连接手动构建 url,因为某些字符需要在有效 url 中编码。如果可能,请使用带参数的 url 助手。

我不知道这是否有效(取决于contactable的实现):

@contactable.redirect_url(email: @contact.email)

如果这不可能,请确保自己进行有效编码:

"#{@contactable.redirect_url}?email=#{ERB::Util.url_encode(@contact.email)}"

【讨论】:

  • 您先生,真是个天才。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
相关资源
最近更新 更多