Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何将\u集合中的选项\u用于与ActiveAdmin组合的\u选择_Ruby - Fatal编程技术网

Ruby 如何将\u集合中的选项\u用于与ActiveAdmin组合的\u选择

Ruby 如何将\u集合中的选项\u用于与ActiveAdmin组合的\u选择,ruby,Ruby,我想从显示帐户表中ID-名称选项的下拉列表中选择一个ID <% f.input :account_id, :as => :select, :collection => options_from_collection_for_select(Account.all, 'id', 'name'), :label=> 'ID' %> 当我点击文本框时,我希望看到如下选项 1-琼斯 牛仔裤 3-史密斯 等 但是在当前代码中,只有Jones、Jeans、Smith等。如何自定

我想从显示帐户表中ID-名称选项的下拉列表中选择一个ID

<% f.input :account_id, :as => :select, :collection => options_from_collection_for_select(Account.all, 'id', 'name'), :label=> 'ID' %>
当我点击文本框时,我希望看到如下选项 1-琼斯 牛仔裤 3-史密斯 等 但是在当前代码中,只有Jones、Jeans、Smith等。如何自定义text_方法? 谢谢

返回一个选项标记字符串,该字符串是通过在集合上迭代并将调用value\u方法的结果指定为选项值,将text\u方法指定为选项文本而编译的

options_from_collection_for_select(Account.all, 'id', 'name')
意味着您正在遍历所有帐户记录,并为每个记录调用Account.id作为value\u方法,Account.name作为text\u方法。您不能使用此帮助程序来存档所需内容,因为预期的选择选项还包括索引号

更好地满足你的需要。将选项\u从\u集合\u替换为\u选择。。。按以下代码分类

options_for_select(Account.all.each_with_index{ |acc, index| [acc.id, "#{index+1} - #{acc.name}"] })
注:

您应该将Account.all.each_与_索引{acc,index{acc.id,{index+1}-{acc.name}}一起移动到一个helper方法中 您还可以通过将id作为选项\u的第二个参数传递给\u select来设置选择器的选定值 更新:


如果前缀号是记录id,则可以使用\u选择的\u集合\u中的选项。您只需要在帐户模型内声明一个实例方法,如下所示:

def name_with_id_prefix
  "#{id} - #{name}"
end
然后在视图中,调用新方法而不是“name”


对不起,我的意思是1-Jones表示Jones的帐户ID是1号,而不是索引。我不知道如何映射这个OO nvm,我使用选项_for_selectAccount.select:id,:name.map{{e.id}-{e.name},e.id]}非常感谢,如果前缀号是记录的id,您可以在帐户模型中声明一个实例方法,返回字符串包括记录id+名称。我已经更新了我的答案。
options_from_collection_for_select(Account.all, 'id', 'name_with_id_prefix')