如何以自定义顺序显示 ransack 复选框

How to display ransack checkbox in custom order

我正在构建一个 rails 工作应用程序并使用搜查 gem。在创建工作时 post,用户可以从集合中选择工作类型。 这是

的代码
<%= f.input :role, collection: ["Fullstack Developer", "Backend 
 Developer", "Frontend Developer", "Engineer", "IOS Developer", 
 "Android Developer", "Designer", "Business Developer"], :label => 
 "Role" %>

在我的工作目录中,我用搜查来显示这个集合。代码如下

<div class="filter-style">
  <h4>Roles</h4>
  <% new_roles = [] %>
  <%= search_form_for @search, :class => 'filters_click' do |f| %>
    <% @jobs.each do |job| %>
      <% if job.role? %>
        <% new_roles << job.role %>
      <% end %>
    <% end %>

    <% new_roles.uniq.each do |new_role| %>
      <div class="styled-input-container">
        <a>
          <label>
            <%= check_box_tag('q[role_eq_any][]', new_role) %>
              <%= new_role %>
          </label>
        </a>
      </div>
    <% end %>
  <% end %>
</div>

我想要的是按照与工作新页面中相同的顺序显示集合。比如我想按"Fullstack Developer"、"Backend Developer"等顺序显示

我现在能想到的最好的方法是执行以下操作。

  1. 首先按照您希望数组的顺序创建一个变量。

    <% role_order = [
      "Fullstack Developer", "Backend Developer",  "Fronten Developer",
      "Engineer",            "IOS Developer",      "Android Developer",
      "Designer",            "Business Developer"
    ] %>
    
  2. 收集您要展示的角色。

    <% new_roles = @jobs.map(&:role).select(&:present?).uniq %>
    
  3. 使用Array#& 方法对数组进行排序。这将取两个数组的交集(输出两个数组中的项目)。按照调用方法所在的数组(第一个数组)确定的顺序。

    <% new_roles = role_order & new_roles %>
    

Note: If you are missing elements in your role_order array they will not be in your new_roles array after step 3. Make sure all possibilities are present in role_order. If you want some extra security that you're not missing out any elements you could raise an excepion.

Furthermore the intersection also removes double elements. That's why I made sure that it didn't contain double elements (see step 2) before making the intersection, otherwise my example below wouldn't work (since the size is never the same if double elements are removed).

引发异常的示例:

<% new_roles2 = role_order & new_roles %>
<% raise 'Missing roles in role_order array!' unless new_roles.size == new_roles2.size %>

或者,您可以为工作角色制作模型并添加订单属性。比按该属性获取实例顺序时。

<% new_roles = Role.where(id: @jobs.select(:role_id)).order(:order_attr) %>