vendredi 2 mars 2018

Active Admin with join table relation

I am configuring Active Admin. Everything is running apart from a join table, which connects the magazine resource with the keyword resource. One magazine is defined by multiple keywords and a keyword can define multiple magazines.

I have two models:

### models/magazine.rb

class Magazine < ActiveRecord::Base
    attr_accessible :colour, :cover_alt, :description, :number, :short, :title_id

    has_and_belongs_to_many :keywords, :join_table => "magazines_keywords" 
    belongs_to :title, :class_name => "Keyword", :foreign_key => "title_id"
end


### models/keywords.rb

class Keyword < ActiveRecord::Base
  attr_accessible :word, :description

  has_and_belongs_to_many :magazines, :join_table => "magazines_keywords"
end

And a join table:

### models/magazines_keyword.rb
class MagazinesKeyword < ActiveRecord::Base
  attr_accessible :magazine_id, :keyword_id

  belongs_to :magazine
  belongs_to :keyword
end

This setting works for the views of my rails app, and I have the index and show section of my AA magazine resource working, but the form (for new and edit) does not work:

ActiveAdmin.register Magazine do
    menu :priority => 1

    form do |f|
        f.semantic_errors *f.object.errors.keys
        f.inputs "Magazine Details" do
            f.input :title_id, :label => 'Title', :as => :select, :collection => Keyword.all.map{ |u| ["#{u.word.capitalize}", u.id] }
            f.inputs :magazines_keywords do
                f.has_many : magazines_keywords do |s|
                    s.input :keyword, :as => :select, :multiple => true, :collection => MagazinesKeyword.all.map { |u| ["#{u.keyword.word.capitalize}", u.id] }
                end
            end
        end
        f.actions
    end

    show do
        panel "Magazine Details" do
            attributes_table_for magazine do
                row "Keywords", :keyword do |m|
                    m.keywords.map { |d| d.word }.join(", ").html_safe
                end
            end
        end
        active_admin_comments
    end
end

When running the app i get NoMethodError in Admin/magazines#edit

Where /active_admin/resource/edit.html.arb line #1 raises undefined method 'klass' for nil:NilClass

I can display all the keywords in the form section with:

f.input :magazines_keywords, :as => :check_boxes, :multiple => true, :collection => MagazinesKeyword.all.map{ |u| ["#{u.keyword.word.capitalize}", u.id] }

But when I try to write them it does not work. Editing the values does not work either.

Where am I missing something? How can I get this working?

Aucun commentaire:

Enregistrer un commentaire