1
votes

I got a weird problem in activeadmin in rails project.
I have created new rails project and two tables as followings.

rails g model category title:text

rails g model subcategory category:references title:text

subcategory belongs to category with the foreign key "category_id" by reference keyword. I have changed the category and subcategory models as the following.

class Category < ActiveRecord::Base
    has_many :subcategories, dependent: :destroy
end

and

class Subcategory < ActiveRecord::Base
  belongs_to :category
  default_scope -> { order(created_at: :desc) }
end

I added the activeadmin gem in the Gemfile and installed.

ActiveAdmin.register Category do

    permit_params :title

end

ActiveAdmin.register Subcategory do

    permit_params :category_id, :title

end

I logged in successfully.
I added new category. If I click the subcategory in order to create new subcagegory, category item brings errors like the image. enter image description here

I want to show the categories added by me. Best Regards.

1

1 Answers

5
votes

That's no error.

Those are category objects. It's now left for you to decide which attribute of the category object you want shown. Name?, Description?

You can have a form like so:

ActiveAdmin.register Subcategory do
  permit_params :name, :description, :category_id

  form do |f|
    f.semantic_errors *f.object.errors.keys

    f.inputs "Details" do
      f.input :name
      f.input :description
      f.input :category_id, :as => :select, :collection => Category.all.collect {|category| [category.name, category.id] }
    end
    f.actions
  end
end

Note the line: f.input :category_id, :as => :select, :collection => Category.all.collect {|category| [category.name, category.id] }

I'm saying to populate the subcategory field with all existing categories, display their names, and use their IDs.

Hope this helps.