Cninroh
Cninroh

Reputation: 1796

How to define form select values via model in Rails?

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
end

and

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

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>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% 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?

Upvotes: 1

Views: 1230

Answers (2)

cdesrosiers
cdesrosiers

Reputation: 8892

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.

Upvotes: 1

Thanh
Thanh

Reputation: 8604

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

Upvotes: 0

Related Questions