Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

arrays - Multiple select with custom data

I have a form with a multiple select like this:?

.form-row__select
? ? ? ? = f.collection_check_boxes(:game_ids, @games, :id, :name)

The collection @games worked because the data was returned this way:

=> #<Game:0x00007fa12c3a9560
?id: 5,
?name: :example,
?active: true,
?...

But now I need to add custom data to my collection and I was not able to make the multiple select work:

game = Game.enabled.includes(:category)
? ? @games = game.map do |s|
?? ? ? [[s.category.name, I18n.t(s.type_code, scope: 'enum.type.name')].join(' - '), s.id]
? ? end
@games.sort!

The result of the above method is an array of array like this:

[["Example one - Category X", 5],
["Example four - Category Y", 1]]
...

How can I make a multiple select using the array above and showing its strings so they can be selected? Thank you so much for your help!

question from:https://stackoverflow.com/questions/65941518/multiple-select-with-custom-data

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
class Game < ApplicationRecord
  # ...
  def my_fancy_pants_name
    [s.category.name, I18n.t(s.type_code, scope: 'enum.type.name')].join(' - ')
  end
end
.form-row__select
   = f.collection_check_boxes(:game_ids, @games, :id, :my_fancy_pants_name, multiple: true)

If you're bothered by putting this logic in the model you can go with a decorator. You can also pass a block to customize the input and label further as detailed in the docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...