How to define form select values via model in Rails?


April 2019


1.1k time


I created a simple model called Categories, which is connected to Platforms model.

class Platform < ActiveRecord::Base
    attr_accessible :name, :url, :country, :categories
   belongs_to  :category


class Category < ActiveRecord::Base
  attr_accessible :name
  has_many :platforms

I also successfully have form for creating new Platforms :

<%= simple_form_for(@platform) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :name %>
    <%= f.input :url %>
    <%= f.input :country %>
    <%= f.label :category %>
    <%= f.collection_select(:category_id, @categories, :id, :name, :include_blank => "Please select") %>

  <div class="form-actions">
    <%= f.button :submit %>
<% end %>

Unfortunately ,since model Category is new, dropdown currently has only 1 value "Please selected". How do I add new values to this select, preferably via the model?

2 answers


In your new action of PlatformsController, add @categories = Category.all , so you will have all category.


Note that with simple_form, you can automatically generate the drop-down using

<%= f.association :category %>

This will automatically populate the list with categories from the database. See the documentation for more tips.

EDIT: Categories simply have to be added separately. You can either manually seed your database with categories with the db/seeds.rb script or through the rails console. Or you can allow users to add categories through a separate form and controller.

For example, to create a few categories in the console, run rails c from the command line and run Category.create!(name: "Name") for a few names.