Reputation: 12650
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
Reputation: 54882
An example of check boxes of Colors:
# 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.
# 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.
# 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' ] }
It depends on what you need:
Upvotes: 1