Rails 3, the best way to stay dry with radio shortcuts?

Suppose for an integer field named "favfood" we represent the choice of the switch as

0 indicates "no favorite"
1 indicates "Wine and cheese"
2 indicates "Burger with everything"

Our _edit view displays radio buttons with friendly captions above

In the / show view and / index view (and in several other places), when we show the user's preference, the same long text is displayed.

Non-DRY seems to put literal lines next to each switch in _edit, and then provides some logic to display the SAME literal line in / show and / index, etc. etc. based on the current value.

In addition, we must reuse the SAME logic, which says that if value = 1 displays "First choice", if value = 2 displays "Second choice".

What is the "rails-way" for handling convenient shortcuts for radio shortcuts so that labels (and their relationship to field values) are defined once?

+3
source share
2 answers

There are two things you must do. One of them uses internationalization (I18n) so that your text is saved in your en.yml file, and you can use these labels instead of lines:

# en.yml
en:
  no_favorite: 'No favorite'
  wine_and_cheese: 'Wine and Cheese'
  burger_with_everything: 'Burger with everything'

# You can then translate the labels like this
I18n.t: no_favorite
I18n.t :wine_and_cheese
I18n.t :burger_with_everything

- , . :

OPTIONS = [:no_favorite, :wine_and_cheese, :burger_with_everything]

:

selected_value = 1
I18n.t OPTIONS[selected_value] # => wine_and_cheese
OPTIONS.index :wine_and_cheese # => 1

, (, User # food_preference), :

class User
  OPTIONS = [:no_favorite, :wine_and_cheese, :burger_with_everything]

  def display_food_preference
    I18n.t OPTIONS[food_preference]
  end
end
+3

, , . Sth :

class User < ActiveRecord::Base
    def favfood_description
        "bla bla" if favfood == 0
    end
end
0

Source: https://habr.com/ru/post/1789641/


All Articles