Rails 5 form_tag with table and radio button

2.1k views Asked by At

I'm a Rails newbie and trying hard to display the radio button checked for a particular record based on its boolean value in the DB(field-name is 'main'). After displaying all table entries, the user can check another radio button and that must again be updated in DB. So basically any one attachment only can be made main.Whatever I do with form_tag, at most the page displays but with no table at all.

attachments/index.html.erb:

<% form_tag user_attachments_path do %>
  <table class="table table-bordered table-striped">
    <thead>
      <tr>
        <th> Select one </th>
        <th> Attachment Name </th>
        <th> Creation Date </th>
        <th> Delete Attachment </th>
      </tr>
    </thead>
    <tbody>
      <% @attachments.each do |attachment| %>
        <%=hidden_field_tag :main, 'attachment.main' %>
        <tr>
          <td><% radio_button_tag "attachment_id", attachment.id, attachment.main %> </td>
          <td><%= attachment.attach.file.basename %></td>
          <td><%= attachment.posting_date %></td>
          <td><%= button_to "Delete", user_attachment_path(current_user, attachment), method: "delete", data: { confirm: 'Are you sure?' }, class: "btn btn-danger btn-outline btn-md" %></td>
        </tr>
      <% end %>
    </tbody>
  </table>
  <br>
  <%= submit_tag "Select Main", :class =>'button' %>
<% end %>

Routes.rb -

post :attachments, to: "attachments#update", as: :attachments

Also, do I access the value of newly checked radio like this in my attachments#update because attachment is a local variable and not sure if it has scope outside index.html

if params[:attachment][:main] == 'checked'

Thanks for all your help.

1

There are 1 answers

2
margo On BEST ANSWER

The erb needs to be amended to display. At the moment it is only executing the code. This might help.

<% form_tag user_attachments_path do %>

should be

<%= form_tag user_attachments_path do %>