2014-12-05 38 views
0

我正在使用自定義集合來顯示具有計劃的複選框。它可以保存,但是當我嘗試編輯時,它會退回給我。爲什麼?編輯模型時未選中「活動管理」複選框

f.inputs for: :schedule, name: 'Employee Schedule' do |sf| 
    sf.input :sunday, as: :check_boxes, collection: available_hours, method: :to_s 
    sf.input :monday, as: :check_boxes, collection: available_hours, method: :to_s 
    sf.input :tuesday, as: :check_boxes, collection: available_hours, method: :to_s 
    sf.input :wednesday, as: :check_boxes, collection: available_hours, method: :to_s 
    sf.input :thursday, as: :check_boxes, collection: available_hours, method: :to_s 
    sf.input :friday, as: :check_boxes, collection: available_hours, method: :to_s 
    sf.input :saturday, as: :check_boxes, collection: available_hours, method: :to_s 
end 

def available_hours 
    (0..23).map { |h| ["#{h}h às #{h.next}h", h] } 
end 

helper_method :available_hours 

回答

2

我發現這個問題的解決方案

我收集保持不變

def available_hours 
    Array(0..23) 
end 

我的形式將有:member_label參數接收一個Proc,這將改變之後收集已經聚集

member_label: Proc.new { |h| "#{h}h às #{h.next}h" } 

修改後:

sf.input :sunday, as: :check_boxes, collection: available_hours, member_label: Proc.new { |h| "#{h}h às #{h.next}h" } , method: :to_s 

等等......

1

您需要確定哪些複選框被選中這樣的:["#{h}h às #{h.next}h", h, :selected]

def available_hours(_h) 
    (0..23).map { |h| ["#{h}h às #{h.next}h", h, h == _h ? :selected : ''] } 
end 

sf.input :sunday, as: :check_boxes, collection: available_hours(sh.object.sunday), method: :to_s 

...或者類似的東西。

0

這可能是一種不同的情況/需要,但我認爲我爲我的一個項目做了一個解決方案。我創建了一個可以用於ActiveAdmin編輯表單的自定義FormStatic輸入類。通過collection_products

ActiveAdmin.register Collection do 
    form do |f| 
    f.inputs 'Products' do 
     f.input :products, as: :products 
    end 
    end 
end 

收集的has_many產品:

module ActiveAdmin 
    module Inputs 
    class ProductsInput < ::Formtastic::Inputs::CheckBoxesInput 
     def choice_html(choice) 

     html_options = label_html_options.merge(
      :for => choice_input_dom_id(choice), 
      :class => checked?(choice[1]) ? 'checked' : nil 
     ) 

     template.content_tag(:label, choice_label(choice), html_options) 
     end 

     def collection 
     super.sort {|a, b| a[0] <=> b[0]} 
     end 

     def choice_label(choice) 
     name, id = choice 
     product = Product.find(id) 

     name = '' 
     name << template.content_tag(:span, product.human_state_name, class: 'status_tag important') + ' ' unless product.on_sale? 
     name << product.name 

     (hidden_fields? ? 
      check_box_with_hidden_input(choice) : 
      check_box_without_hidden_input(choice)) + \ 
     template.image_tag(product.listing.thumb, width: 60).html_safe + \ 
     template.content_tag(:span, name.html_safe, class: 'choice_label') 
     end 
    end 
    end 
end 

然後你可以在這樣一個編輯框使用它。