Option lists with simple_form

Written . Tagged Ruby, Ruby on Rails, simple_form.

This is the pattern I’ve used lately to enumerate values for simple_form select options:

Values:

app/models/order/status.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Order
  class Status
    KEYS = [
      NEW       = "new",
      INVOICED  = "invoiced",
      PAID      = "paid",
      SHIPPED   = "shipped"
    ]

    def self.keys
      KEYS
    end

    def self.all
      keys.map { |key| new(key) }
    end

    def initialize(key)
      @key = key
    end

    # simple_form automatically uses `id` for the option value.
    def id
      @key
    end

    # simple_form automatically uses this for the option text.
    def name
      I18n.t(@key, scope: :"models.order.statuses")
    end
  end
end

View:

app/views/orders/_form.html.erb
1
2
3

<%= f.input :status, collection: Order::Status.all %>

And you can validate like this:

app/models/order.rb
1
2
3
class Order < ActiveRecord::Base
  validates :status, inclusion: { in: Status.keys }
end

If you have something better, let me know!