使用“简单表单”为group_select中的选项指定属性

时间:2015-07-02 13:52:02

标签: ruby-on-rails forms html-select simple-form custom-data-attribute

我很清楚使用Simple Form将数据属性分配给传统选择框中的选项但是当涉及到分组选项时,我似乎遇到了一些问题。我找到了一个post,解释了如何做到这一点简单形式:

<%= f.select :game_id, grouped_options_for_select(@consoles.map{ |console| [console.name, console.games.map{ |g| [g.title, g.id, {'data-game'=> g.title.downcase.gsub(/\s+/, "-")}] } ] }, selected_key = f.object.game_id) %>

当我尝试将其翻译成适当的语法时,我收到此错误:

undefined method 'games' for ["PS3", []]:Array

<%= f.input :game_id, as: :grouped_select, collection: @consoles.map{ |console| [console.name, console.games.map{ |g| [g.title, g.id, {'data-game'=> g.title.downcase.gsub(/\s+/, "-")}] } ] }, group_method: :games, include_blank: "Select a game", input_html: {class: "boost__game"} %>

模型

class Game < ActiveRecord::Base
  # attributes: title
  has_and_belongs_to_many :consoles
end


class Console < ActiveRecord::Base
  # attributes: name
  has_and_belongs_to_many :games
end

什么似乎是问题?

1 个答案:

答案 0 :(得分:2)

试试这个,

<%= f.input :game_id, as: :grouped_select, collection: @consoles.map{ |console| [console.name, console.games.map{ |g| [g.title, g.id, {'data-game'=> g.title.downcase.gsub(/\s+/, "-")}] } ] }, group_method: :last, include_blank: "Select a game", input_html: {class: "boost__game"} %>