使用MongoDB時將選項分組的最佳方式是什麼?如何使用Mongoid在rails中生成optgroup?
我使用Mongoid,當我嘗試這個辦法:
<%= field.select :resource_id,
grouped_options_for_select(Resource.all.group_by{"resource_type_id"}.map {|k,m|
[m.first.title, m.first.id] }),:prompt => true %>
它給了我下面的錯誤:
undefined method `map' for "5177e6a5359f105f89000001":Moped::BSON::ObjectId
雖然我要找:
<select>
<optgroup label="RT1"> <!-- RT1 is the name of resource type -->
<option value="5177e6a5359f105f89000001">Res1</option>
</optgroup>
</select>
而且,在控制檯中,Resource.all.group_by{"resource_type_id"}
的輸出是
=> {"resource_type"=>[#<Resource _id: 5177e6a5359f105f89000001,
created_at: 2013-04-24 14:05:25 UTC, updated_at: 2013-04-24 14:54:14 UTC,
title: {"en"=>"Res1"}, slug: {"en"=>"res1"}, content:
{"en"=>"This is the content for First Resource."},
excerpt: {"en"=>"This is the content for First Resource."}, published: true,
resource_type_id: "5177e3ba359f10d345000004">]}
而預期結果是
=> {"RT1"=>[#<Resource _id: 5177e6a5359f105f89000001,
created_at: 2013-04-24 14:05:25 UTC, updated_at: 2013-04-24 14:54:14 UTC,
title: {"en"=>"Res1"}, slug: {"en"=>"res1"}, content:
{"en"=>"This is the content for First Resource."},
excerpt: {"en"=>"This is the content for First Resource."}, published: true,
resource_type_id: "5177e3ba359f10d345000004">]}