编辑模型时未选中“活动管理”复选框
问题描述:
我正在使用自定义集合来显示具有计划的复选框。它可以保存,但是当我尝试编辑时,它会退回给我。为什么?编辑模型时未选中“活动管理”复选框
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
答
我发现这个问题的解决方案
我收集保持不变
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
等等......
答
您需要确定哪些复选框被选中这样的:["#{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
...或者类似的东西。
答
这可能是一种不同的情况/需要,但我认为我为我的一个项目做了一个解决方案。我创建了一个可以用于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
然后你可以在这样一个编辑框使用它。