:has_many relations in Active Admin

In this post we are going to explain how to setup a :has_many relation in Active Admin for a Rails application.

Let’s assume that we have a couple of models: Articles and Categories with the following fields each one:

#Article Model
:title
:author
:description

and

#Categories Model
:name

Normally you will create a :has_and_belongs_to_many relation between the models as you normally will on Rails. (See the official documentation if you have any doubt).

After that you will create the Active Admin models using the following commands:

rails generate active_admin:resource Article
rails generate active_admin:resource Category

Now comes the tricky part: how to create the index, show and form views in Active Admin to allow selecting and showing Article’s categories.

Open the Active Admin view for Article that is located under app/admin/article.rb and add the following code:

permit_params :title, :author, :description, category_ids: []
index do
selectable_column
id_column
column :title
column :author
column :description
column :categories do |article|
table_for article.categories.order('name ASC') do
column do |category|
category.name
end
end
end
end

show do
attributes_table do
row :title
row :author
row :description
table_for article.categories.order('name ASC') do
column "Categories" do |category|
link_to category.name, [ :admin, category ]
end
end

end
end

form do |f|
f.inputs "Add/Edit Article" do
f.input :name
f.input :author
f.input :description
f.input :categories, :as => :check_boxes
end
actions
end

As you can see inside the tables creating a special inner table is required for best display. I add the link to the category edit in so it’s easy to edit/view the category from the article table.

To add checkboxes for category select it’s as simple as adding f.input :categories, :as => :check_boxes to your form view.


If you have any question or suggestion let me know or leave a comment.

Author: Eng. Alberto Aragón Alvarez

If you like it, clap. For more histories like this one follow our publication on Medium.

If you want to collaborate with us please visit our web site:

www.alturasoluciones.com