Formtastic / ActiveAdmin multi-select many to many checkbox association issue

mattwallace picture mattwallace · Jun 6, 2012 · Viewed 8.1k times · Source

I am using activeadmin and it has formtastic built in as many of you who use it know. I have a model called Project that has a many to many association with ProjectResources.

My custom "edit" and "creation" form in active admin for Project looks like so.

form do |f|
          f.inputs "Project" do
            f.input :name, :input_html => { :readonly => true }
          end
          f.inputs "Resources" do
            f.input :id, :label => "Selected Resources",  
                :as => :check_boxes, 
                :multiple => true, 
                :collection => ProjectResource.all,
                :selected => @resources
          end
          f.buttons
    end

My checkboxes render just fine and I don't get any errors at this point. The problem if you may have guessed is that when rendering the "edit" page I would like to show items in the checkbox area as "selected" if the Project has a ProjectResource as an association already.

Right now the checkboxes all show a deselected state. I am using the latest version of activeadmin and formtastic has the following versions installed. (2.2.0, 2.1.1, 2.1.0, 2.0.2, 1.2.4)

Not sure what version activeadmin uses at this point. My guess is the latest version.

Answer

nothing-special-here picture nothing-special-here · Jul 9, 2012

For me, simple:

ActiveAdmin.register Subscription do

  form do |f|
    f.inputs do
      f.input :users, as: :check_boxes
      # other fields...
    end
    f.buttons
  end
end

just works.

More Code:

-User class

class User < ActiveRecord::Base
  has_and_belongs_to_many :users
  attr_accessible :fields...
end

-Subscription Class

class Subscription < ActiveRecord::Base
  has_and_belongs_to_many :subscriptions
  attr_accessible :fields...
end

PS I am using ActiveAdmin 0.4.2 and Formtastic 2.0.2.