Dreams
Dreams

Reputation: 8506

How to iterate data from database to become a radio button in template?

I am using Rails 4.2 and Ruby 2.1.5

Here is my radio button code of my new template:

<%= form_for @api, :url => commons_path do |f| %>
  <div class="form-group">
      <%= f.label :status, "Status",  class: "col-sm-2 control-label" %>
        <div class="col-sm-8">
          <%= f.radio_button :status, 'success' %>
          <%= label_tag(:status, "Success") %> 
          <%= f.radio_button :status, 'fail' %>
          <%= label_tag(:status, "Fail") %> 
          <%= f.radio_button :status, 'exception' %>
          <%= label_tag(:status, "Exception") %> 
       </div>
      </div>
</end>

Now , I would like to create a new table in database to store different status.

create_table "statuses", force: :cascade do |t|
  t.string   "status"
  t.datetime "created_at"
  t.datetime "updated_at"
end

How to iterate data from database to become a radio button automatically in template so I don't have to hardcode radio button in template every time.

Upvotes: 0

Views: 90

Answers (1)

Pablo
Pablo

Reputation: 1093

You can iterate all the Status records (*).

In your controller, you can add:

@statuses = Status.all

And in your view:

<%= form_for @api, :url => commons_path do |f| %>
  <div class="form-group">
    <%= f.label :status, "Status",  class: "col-sm-2 control-label" %>
    <div class="col-sm-8">
      <% @statuses.each do |status| %>
        <%= f.radio_button :status, status.status %>
        <%= label_tag(:status, status.status) %> 
      <% end %>
    </div>
  </div>
<% end %>

(*) Be careful if you have hundreds of statuses since this loads all in memory at once.

Upvotes: 1

Related Questions