Rails 4- Как создать флажки в форме, где значения берутся из переменной класса, которая является массивом

У меня есть модель с именем task.rb следующим образом:

 # == Schema Information
 #
 # Table name: tasks
 #
 #  id            :integer          not null, primary key
 #  inputpath     :string(255)
 #  outputpath    :string(255)
 #  inputsize     :integer
 #  outputsize    :integer
 #  operator      :string(255)
 #  operationtype :string(255)
 #  created_at    :datetime
 #  updated_at    :datetime
 #

 class Task < ActiveRecord::Base

 @@tasktypes = ["csv", "db"]

 def tasktypes
   @@tasktypes
 end


 end

Что я пытаюсь сделать в представлении, отображаемом для «нового» действия, я хочу дать пользователю возможность в качестве флажков выбрать одно или несколько значений из @@tasktypes, которые будут значением для атрибута: «тип операции»

Это моя форма:

 <%= form_for(@task) do |f| %>
   <% if @task.errors.any? %>
     <div id="error_explanation">
       <h2><%= pluralize(@task.errors.count, "error") %> prohibited this task from being saved:</h2>

       <ul>
       <% @task.errors.full_messages.each do |msg| %>
         <li><%= msg %></li>
       <% end %>
       </ul>
     </div>
   <% end %>

   <div class="field">
     <%= f.label :inputpath %><br>
     <%= f.text_field :inputpath %>
   </div>
   <div class="field">
     <%= f.label :outputpath %><br>
     <%= f.text_field :outputpath %>
   </div>
   <div class="field">
     <%= f.label :inputsize %><br>
     <%= f.number_field :inputsize %>
   </div>
   <div class="field">
     <%= f.label :outputsize %><br>
     <%= f.number_field :outputsize %>
   </div>
   <div class="field">
     <%= f.label :operator %><br>
     <%= f.text_field :operator %>
   </div>
   <div class="field">
     <%= f.label :operationtype , "What would you like to do with the file?"%><br>
     <%= f.collection_check_boxes(:operationtype,?? ,@@tasktypes, ?? %>
   </div>
   <div class="actions">
     <%= f.submit %>
   </div>
 <% end %>

ОБНОВИТЬ:

Я только что сделал небольшое изменение в атрибуте модели «тип операции» со строки на текст, а также сериализовал его в модели, см. Ниже:

 # == Schema Information
 #
 # Table name: tasks
 #
 #  id            :integer          not null, primary key
 #  inputpath     :string(255)
 #  outputpath    :string(255)
 #  inputsize     :integer
 #  outputsize    :integer
 #  operator      :string(255)
 #  operationtype :text
 #  created_at    :datetime
 #  updated_at    :datetime
 #

 class Task < ActiveRecord::Base

serialize :operationtype, Array

@@tasktypes = ["csv", "db"]
#validates :inputpath, :outputpath, presence => {:message => "Must provide an inputpath and outputpath for file processing" }

 def self.tasktypes
@@tasktypes
 end



 end

Как вы можете видеть выше, я пытаюсь понять, как заставить флажки работать. Буду признателен, если кто-то поможет с этим. Я просмотрел документы, и, похоже, нет способа заставить это работать, но, может быть, есть хак?


person banditKing    schedule 09.02.2014    source источник


Ответы (1)


Вы можете использовать помощника check_box_tag, вроде этого

<% tasktypes.each do |type| -%>
  <label><%= type %></label>
  <%= check_box_tag 'task[operationtype][]', type %>
<% end -%>

Хотя я бы использовал его как свойство массива в модели, а затем использовал помощник select с включенной опцией multiple. Было бы проще отслеживать и обрабатывать состояние выбранных значений

person Nikolay    schedule 09.02.2014
comment
Я только что изменил атрибут типа операции на массив (тест), см. обновленный раздел выше. Учитывая это Как заставить эту работу работать, используя ваше предложение использовать select? Спасибо - person banditKing; 10.02.2014
comment
Это должно выглядеть примерно так f.select :oprationtype, Task.tasktypes.map{|name| [name, name]}, multiple: true см. эту ссылку для более подробной информации apidock.com/rails/ ActionView/Helpers/FormOptionsHelper/выбрать - person Nikolay; 10.02.2014
comment
Спасибо за вашу помощь. - person banditKing; 10.02.2014