【问题标题】:Assigning attributes to options in a group_select using Simple Form使用简单表单将属性分配给 group_select 中的选项
【发布时间】:2015-07-02 23:04:04
【问题描述】:

我很清楚使用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

似乎是什么问题?

【问题讨论】:

  • 控制台是一个数组吗?
  • 它是一个与Game 模型有has_and_belongs_to_many 关系的模型。
  • 我认为错误出在其他地方...
  • 您确定因为使用f.select 方法可以正常工作吗?

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


【解决方案1】:

试试这个,

<%= 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"} %>

【讨论】:

  • 使用此代码,选择框的选项会变成 f.select 哈希中提供的所有键:as, grouped_select, collection, include_blank, class
  • 您的收藏价值的格式是否为[['Authors', ['Jose', 'Carlos']], ['General', ['Bob', 'John']]]。我的意思是,@consoles.map{ |console| [console.name, console.games.map{ |g| [g.title, g.id, {'data-game'=&gt; g.title.downcase.gsub(/\s+/, "-")}] } ] } 的格式为 [['Authors', ['Jose', 'Carlos']], ['General', ['Bob', 'John']]]
  • 是的。所以选择框的组标题将是控制台的名称,嵌套选项将是游戏的标题。希望这会将您的示例转化为我目前的情况:[['Xbox One', ['Halo', 'Tomb Raider']], ['PS4', ['Drive Club', 'Last of Us']]]
  • 现在,我知道您的错误是什么...错误在 group_method 中。你在集合中得到的是一个数组。所以它试图访问那个 Array.games
  • 这可行,但我仍然需要将数据属性应用于选项。
猜你喜欢
  • 2015-03-16
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
相关资源
最近更新 更多