在Rails中为form_tag添加名称空间

时间:2019-06-10 10:26:33

标签: ruby-on-rails shopify-app

我正在使用bootstrap_form gem在Rails中生成表单。在表单视图中,我使用的是form_tag而不是form_for

  <%= bootstrap_form_tag url: 'metafields' do |f| %>
    <%= f.hidden_field :owner_id, value: params[:owner_id] %>
    <%= f.text_field :namespace, placeholder: 'Namespace of metafield' %>
    <%= f.text_field :key, placeholder: 'Key of metafield' %>
    <%= f.text_area :description, placeholder: 'Description about metafield' %>
    <%= f.select :type, [['String', 'string']], class: 'selectpicker' %>
  <% end %>

是否可以使用包含前缀名称空间(如params[:metafield][:owner_id])的参数提交此表单。

当我尝试过

<%= bootstrap_form_tag url: 'metafields', namespace: 'metafield' do |f| %>

它生成下面的输入,这不是我想要的

<input placeholder="Key of metafield" name="key" id="metafield_key" class="form-control" type="text" kl_vkbd_parsed="true">

2 个答案:

答案 0 :(得分:1)

this开始,form_tag不支持form_for之类的命名空间。因此,我找到了一种解决方法,如下所示,该方法会生成正确的name输入,就像我们使用form_for

    <%= bootstrap_form_tag url: 'metafields' do |f| %>
      <%= f.hidden_field :owner_id, value: @owner_id %>
      <%= f.hidden_field :owner_class, value: @owner_class %>
      <%= f.text_field :'metafield[namespace]', label: 'Namespace', placeholder: 'Namespace of metafield' %>
      <%= f.text_field :'metafield[key]',label: 'Key', placeholder: 'Key of metafield' %>
      <%= f.text_field :'metafield[value]',label: 'Value', placeholder: 'Key of metafield' %>
      <%= f.select :'metafield[value_type]', [['String', 'string']], label: 'Type', class: 'selectpicker' %>
      <%= f.text_area :'metafield[description]', label: 'Description', placeholder: 'Description about metafield' %>
      <%= f.submit 'Submit', class: 'btn btn-outline-dark float-right' %>
    <% end %>

答案 1 :(得分:1)

quyetdc的答案是一种解决方法,除非您具有动态表单,否则这是一种更简洁的方法

  <%= bootstrap_form_tag url: 'metafields' do |f| %>
    <%= f.fields_for :metafield do |mf| %>
      <%= mf.hidden_field :owner_id, value: params[:owner_id] %>
      <%= mf.text_field :namespace, placeholder: 'Namespace of metafield' %>
      <%= mf.text_field :key, placeholder: 'Key of metafield' %>
      <%= mf.text_area :description, placeholder: 'Description about metafield' %>
      <%= mf.select :type, [['String', 'string']], class: 'selectpicker' %>
  <% end %>