简体   繁体   中英

Add namespace for form_tag in Rails

I'm using bootstrap_form gem for form generating in Rails. In my form view, I am using form_tag instead of 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 %>

Is there a way to submit this form with params including prefix namespace like params[:metafield][:owner_id] .

When I tried with

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

It generates below input, which is not what I want

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

As from this , form_tag does not support namespace like form_for . Thus, I found a workaround as below, which generate correct name for input as if we use 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 %>

quyetdc's answer is a way to go unless you have dynamic forms, here is a cleaner way

  <%= 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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM