【问题标题】:Rails & Handlebars: bad URI error for template URLRails & Handlebars:模板 URL 的错误 URI 错误
【发布时间】:2018-08-15 21:54:10
【问题描述】:

在一个较旧的项目中,我使用了这个 Handlebars 模板:

script id='user-form-template' type='text/x-handlebars-template'
  = simple_form_for User.new, method: 'post', url: '/users/{{id}}' do |f|
    = hidden_field_tag :_method, '{{method}}'
    = f.input :name
    = f.input :email
    ...

这通过此操作在 Handlebars 模板中创建了一个表单:

action="/users/{{id}}"

我用它来创建新的(将 id 留空,将 _method 设置为 POST) 并编辑现有的 (设置 id,将 _method 设置为 PATCH) 用户。

在我的新项目(Rails 5.2.1)中,我收到 URI::InvalidURIError 消息:

bad URI(is not URI?): /users/{{id}}

有没有更好的方法来构建带有表单的模板?我想让 SimpleForm 自动创建引导表单 HTML。

【问题讨论】:

    标签: ruby-on-rails url handlebars.js ruby-on-rails-5 simple-form


    【解决方案1】:

    由于您使用的是simple_form_for User.new,而不是simple_form_for @existing_user,我敢打赌您需要删除URL 的/{{id}} 部分。如果您正在尝试创建一个新用户,您只想发布到 /users

    【讨论】:

    • 在我之前的项目中,我可以将表单用于新用户和现有用户,效果很好。如果没有 {{id}},我只能将它用于新用户,因为我无法使用 Handlebars 添加它。 SimpleForm 使用 User.new 获取模型信息,URL 无关紧要。在这种情况下,括号是唯一的问题。
    【解决方案2】:

    我把模板改成

    = simple_form_for User.new, method: 'post', data: { url: '/users/{{id}}' }
    

    在替换模板中的占位符后,我将data-url 改回url

    $('form').attr('action', $('form').data('url'));
    

    不是最好的解决方案,但我可以使用它。

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多