Rails 4 -Simple Form how to save key and display v

2019-08-14 18:11发布

问题:

I'm trying to make an app in Rails 4. I use simple form for forms.

I have an attribute called 'self_governance' in my model.

I've written a helper method so that I can define 5 levels which can be stored for this attribute, but which are displayed to the user as options (rather than numbers 1 .. 5).

In my helper, I have:

module PreferencesHelper

    def self_gov_selector
        [
            [ 'tier 1','1'],
            [ 'tier 2','2'],
            [ 'tier 3','3'],
            [ 'tier 4','4'],
            [ 'tier 5','5'],
        ]
    end

In my form, I then have:

<%= f.input :self_governance, :label => "Select your tier", collection: self_gov_selector %>

Then in my show, I'm trying to figure out how to display 'tier 1' instead of '1'.

I have tried:

<%= @preference.self_governance %>

<%= @preference.self_gov_selector %>

I can't find anything that works. They all display 1 instead of Tier 1 in the views.

How can I make this work?

回答1:

The params posted by the form will only include the second value in the array, so you're likely storing your value as an integer in your database table.

A simple solution is to use an enum to map the integers you're storing to the values they represent:

In your Preference model:

enum self_governance: {
                          tier_1: 1,
                          tier_2: 2,
                          tier_3: 3,
                          tier_4: 4,
                          tier_5: 5
                        }

Then update your view accordingly:

<%= @preference.self_governance.try(:humanize) %>

EDIT:

An additional bonus of this approach is that you can replace your helper method with calling the enum directly:

f.input :self_governance, as: :select, label: "your label", collection: Preference.self_governances.map { |key, val| [key.humanize, val] }