我正在使用 Rails 3。A Map
拥有并属于许多Collection
s,反之亦然。
什么已经存在了...
我有一个表单,允许用户选择将放入一个集合中的多个 map 。为此,我将 jQuery UI 与 Selectable 结合使用网格中的方法。
网格是这样构造的:
<ol id="selectable">
<% for map in @user.maps %>
<li class="ui-state-default">
<strong><%= map.title %></strong><br>
<%= image_tag(map.thumbnail_url) %>
</li>
<% end %>
</ol>
看起来像这样:
当用户完成选择时,所选 map (它们的 <li>
标签)将具有类 .ui-selected
.
我需要什么...
我如何将这些选定 map 的 ID 传递给 Controller ,以便将它们添加到新的集合中?我应该在 Controller 中做什么?这里的最佳做法是什么?
我想做什么...
我考虑过为表单编写自定义提交处理程序,它将遍历所有这些
li.ui-selected
并以某种方式尝试提取 ID,然后将它们合并到一个隐藏的表单字段中,最后提交表单。然后,在 Controller 中,我将再次拆分隐藏的表单字段,提取 ID 并从数据库中获取 map 。另一种方法可能是使用
collection_select
,以某种方式与 jQuery Selectable 同步。collection_select
我有:<%= collection_select :collection, :map_ids, @collection.user.maps, :id, :title, { :selected => @collection.map_ids }, { :class => "map_select", :multiple => true, :size => '10', :name => 'collection[map_ids][]' } %>
虽然两者听起来都有些老套。有没有更简单或更像 JS/Rails 的东西?
最佳答案
这是我最终得到的结果。这是我的 collection_select
。
<%= collection_select :collection,
:map_ids,
@collection.user.maps,
:id,
:title,
{ :selected => nil },
{ :class => "map_select hiddenElement", :multiple => true, :size => '10', :name => 'collection[map_ids][]' }
我的个人容器是这样创建的:
<ol id="selectable">
<% for map in current_user.maps %>
<% if @collection.maps.include? map %>
<li class="singleMapContainer ui-selected">
<% else %>
<li class="singleMapContainer">
<% end %>
<div class="singleMapInfo">
<span class="mapId" style="display:none;"><%= map.id %></span>
<strong><%= map.title %></strong><br>
<%= map.created_at %><br>
<%= image_tag(map.thumbnail_url) %>
</div>
</li>
<% end %>
</ol>
这是在提交表单时同步它们的 Javascript:
$("#new_collection, .edit_collection").submit(function(){
// iterate over each selected map container element
$("li.ui-selected").each(function(){
var mapId = $(this).find("span.mapId").html(); // find the map ID
$("#collection_map_ids option[value='" + mapId + "']:first")[0].selected = true; // synchronize the multiple select box
});
return true;
});
关于javascript - 将选定元素从 jQuery UI Selectable 传递到 Rails Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6651295/