Search code examples
ruby-on-railsactiveadminhas-many-throughformtastic

Using HABTM or Has_many through with Active Admin


I've read quite a few of the posts on using active admin with has_many through association but I'm not getting the desired results. Essentially I have 2 models "Conferences" & "Accounts". I need to assign multiple accounts to a conference and multiple conferences to an account. Wether I use HABTM or has_many through doesn't matter to me. I just need to be able to see a dropdown select option when I create a new conference and vice versa on accounts.

Account Model

class Account < ActiveRecord::Base
  attr_accessible :address, :city, :name, :phone, :state, :website, :zip
  has_many :contacts, :dependent => :destroy
  has_many :conferences, :through => :conferenceaccount
end

Conference Model

class Conference < ActiveRecord::Base
  attr_accessible :address, :city, :conferencename, :eventdateend, :eventdatestart, :industry, :phone, :state, :website
  has_many :accounts, :through => :conferenceaccount
end

Conference Account Model

class Conferenceaccount < ActiveRecord::Base
  belongs_to :conference
  belongs_to :account

  attr_accessible :account_id, :conference_id
end

Conference Admin Model

ActiveAdmin.register Conference do 
  form do |f|
      f.inputs "Details" do # Project's fields
          f.input :conferencename
          f.input :address
          f.input :city
          f.input :state         
          f.input :website
          f.input :phone
          f.input :eventdatestart
          f.input :eventdateend
          f.input :industry         
      end
      f.has_many :conferenceaccounts do |app_f|
         app_f.inputs "Conferences" do
           if !app_f.object.nil?
             # show the destroy checkbox only if it is an existing appointment
             # else, there's already dynamic JS to add / remove new appointments
             app_f.input :_destroy, :as => :boolean, :label => "Destroy?"
           end

           app_f.input :account # it should automatically generate a drop-down select to choose from your existing patients
         end
       end      
      f.buttons
  end
end

I keep getting the following error

ActionView::Template::Error (undefined method `klass' for nil:NilClass):
    1: insert_tag renderer_for(:new)
  app/admin/conferences.rb:14:in `block (2 levels) in <top (required)>'

How can I fix this?

Thanks.


Solution

  • Did you try to add below lines to your Conference model?

    # conference.rb
    attr_accessible : conferenceaccounts_attributes
    has_many :conferenceaccounts
    
    # This line after your your relations
    accepts_nested_attributes_for : conferenceaccounts, :allow_destroy => true
    

    see: accept nested attributes for has_many relationship