0

I set category's viewable attribute as an enum

class Category < ActiveRecord::Base
  enum viewable: [:only_self, :friends, :anyone]
end

How should I make them accesible in _form when users edit this attribute? Something like?

<%= form_for(@category) do |f| %>
  <%= f.select(:viewable) %>
<% end %>

UPDATE------

  <%= f.select(:viewable, options_for_select([["description1", "only_self"], ["description2", "friends"], ["description3", "anyone"]])) %>
  1. The description for each is quite repetative, because I need to put them whenever I need to display, not just in the forms. Where should I put them?
  2. In form_for, the f.select does not display the current value of the this field. It always is the first description1.
ZK Zhao
  • 19,885
  • 47
  • 132
  • 206

1 Answers1

2

When using the plural form, rails provides the full key/value array, so you can call Category.viewables for the array, and with the help of options_for_select you'll get a nice functioning dropdown list

<%= form_for(@category) do |f| %>
  <%= f.select(:viewable, options_for_select(Category.viewables)) %>
<% end %>

Updated answers

The description for each is quite repetative, because I need to put them whenever I need to display, not just in the forms. Where should I put them?

You can use the I18n library, assuming your locale is chinese (zh i think) then you could create /config/locales/zh.yml and add something like this

categories:
  viewable:
    only_self: 'some chinese text'
    friend: 'more chinese text'
    anyone: 'well you know'

Then better create some helper that returns the localized options

def options_for_viewables
  { 
    t('categories.viewable.only_self') => 0,
    t('categories.viewable.friends') => 1,
    t('categories.viewable.anyone') => 2
  }
end

The view will become like this

<%= f.select(:viewable, options_for_viewables) %>
Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89
  • I've update my question. Could you help me with this? As for the `description` of enum, I'm using chinese, so the english value is quite unfriendly to my users. – ZK Zhao Feb 21 '15 at 07:47
  • Yeah, it works, Thankyou. But `def options_for_viewables` should just be a block, not `[]` needed. – ZK Zhao Feb 21 '15 at 08:19
  • @Mohammad AbuShady When I did that in your way, I've got an error: '1' is not a valid period_units So, I think [this answer](http://stackoverflow.com/a/24195129/3134155) is the right way doing this. – 18augst Mar 18 '15 at 18:03
  • I can't tell what is the problem with your case, but i know this should work cause I already used this in many cases, if you have a question on SO you can give me the link and I'll take a look – Mohammad AbuShady Mar 18 '15 at 18:22