Kevin Brown
Kevin Brown

Reputation: 12650

Rails checkboxes/form based on YML/DB

I want to create a big checkbox area with maybe about 30 checkboxes. I want, instead of hard-writing each checkbox, to populate this from the db, or from the translation yml. How would I create this loop to do so from a yml? I'm guessing that's bad practice? If so, how to loop for db values?

Upvotes: 1

Views: 700

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

An example of check boxes of Colors:

From YAML:

# controller
def show
  @options = YAML.load(File.read(Rails.root.join('db', 'fixtures', 'checkboxes.yml')))

# view
Check the colors you want:
- @options.each do |option|
  = option
  = check_box_tag 'colors[]', option

# example of received parameters:
params = { colors: [ 'red', 'blue' ] }

# db/fixtures/checkboxes.yml
---
- Blue
- Red
- White
- Black
- Green
- Yellow

This is a static list of pre-defined Colors which means you would need to manually edit the YML file AND restart your server to see the changes on this list.

Is it a disadvantage ? Yes and no, depends on what you want to do.


From DB:

# controller
def show
  @options = Color.all.map{ |color| [color.name, color.id] }

# view
Check the colors you want:
- @options.each do |option_name, value|
  = option_name
  = check_box_tag 'colors[]', value

# example of received parameters:
params = { colors: [1,2,3] } # ids of Color records

This is a dynamic list of Colors that can be maintained easily via the web interface (no need to restart the server). You can do the basic CRUD (create retrieve update delete) actions on these, whereas the YAML file cannot be handled that easy (possibility to re-write and re-load the file on the fly but WAOW such a pain in the ass in comparison to the "Rails' way" with a Color model.


loaded from I18n's translation file:

# implying that en.posts.colors is a list of color names
en:
  # ...
  posts:
    # ...
    colors:
      black: Black
      red: Red
      white: White

# view
- t('posts.colors').each do |i18n_key, color_name|
  = color_name
  = check_box_tag 'colors[]', color_name

# example of received parameters:
params = { colors: [ 'red', 'blue' ] }

How to decide?

It depends on what you need:

  • You need the list to be static? (classic usage: countries, languages, colors, genders, etc.) -> Go for the YAML option
  • You need the list to be dynamic? (classic usage: users, categories, content that can be edited inside the app) -> Go for the Model option

Upvotes: 1

Related Questions