ActiveAdmin Batch Action Dynamic Form

霸气de小男生 提交于 2020-01-13 11:04:47

问题


I am using rails 4 with ActiveAdmin. I created a batch action using a custom form to create a Task with a Build number for every selected Device. Here's what my code looks like:

ActiveAdmin.register Device do

  def get_builds
    builds = []
    Build.all.each do |build|
      builds << [
        "[#{build.resource} - #{build.version}] #{build.file_name}",
        build.id
      ]
    end

    return builds
  end

  batch_action :create_task, form: {
    build: get_builds()
  } do |ids, inputs|

    build = Build.find(inputs[:build])

    Device.where(id: ids).each do |device|
      Task.create({
        device: device,
        build: build
      })
    end

    redirect_to admin_tasks_path
  end

end

My problem is that the list of build in the batch action's form is not refreshing. When I start my app it does have a list of all the available builds but if I add or remove a build, the build list won't be refreshed.

It is of course because the form parameter evaluate my function only once but I can't find any documentation about having a "dynamic" form.


回答1:


ActiveAdmin is caching the class in memory on load, so the builds only get calculated once. To re-calculate on each load, pass a lambda as the value of form, e.g:

form_lambda = lambda do
  builds = Build.all.map do |build|
    ["#{ build.resource } - #{ build.version } #{ build.file_name }", build.id]
  end

  { build: builds }
end

batch_action :create_task, form: form_lambda do
  # ...
end



回答2:


@ahmacleod's approach of recalculation on each load, by passing a lambda as the value for the form worked for me.

But I had to contend with this error

wrong number of arguments (given 1, expected 0)

Worked around with this change:

form_lambda = lambda do |id = nil|
  # ...
end


来源:https://stackoverflow.com/questions/32639649/activeadmin-batch-action-dynamic-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!