• This repository has been archived on 23/Jul/2022
  • Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This extends ActiveAdmin to allow for better editing of associations.

ActiveAdmin Associations

Code Climate Build Status Coverage Status Gem Version

This extends ActiveAdmin to allow for better editing of associations.

Setup

Install the gem

Add this to your Gemfile:

gem 'activeadmin_associations'

Then run bundle install.

Includes styles we'll need

Add @import "active_admin_associations"; to the top of your app/assets/stylesheets/active_admin.css.scss

These styles are used by both the autocomplete functionality and the association tables at the bottom of form pages.

Autocomplete

On many applications you end up with large datasets, trying to select an element from those data sets via a select input (Formtastic's default) is less then ideal for a couple reasons. One, it's hard to navigate a large select list. Two, loading all those records into memory to populate the select list can be time consuming and cause the page to load slowly.

So I've packaged jquery-tokeninput, an autocomplete results controller, and an ActiveRecord macro together to help improve this.

If you aren't interested in using any of this just add this to your application.rb config:

config.activeadmin_associations.autocomplete = false

If you do want it here's how you set it up:

Setting up autocomplete

First, we'll need to make sure the JS and CSS is setup for the admin part of the site.

  • Add //= require active_admin_associations to the top of your app/assets/javascripts/active_admin.js file.

  • Add autocomplete statements to models you want to be able to autocomplete in the admin.

    • This first parameter it takes is a column/attribute name like :title.
    • The second parameter is an options hash which for now only uses 1 value :format_label Format Label isn't needed for jquery.tokeninput.js but it is useful when using jQueryUI's autocomplete in other parts of your site. It can allow you to custom format the display label for the autocomplete results displayed by jQueryUI. The :format_label option should be either a symbol that is a name of a method on an instance of the model, or a proc (or anything that responds to call) that takes 1 parameter which will be the record. Example:
      autocomplete :name, :format_label => proc {|speaker|
      label =  "<span id="speaker-#{speaker.id}">#{speaker.name} ("
      label << "#{speaker.position}, " unless speaker.position.blank?
      label << "#{speaker.talk_count} talk#{'s' unless speaker.talk_count == 1})"
      label
      }
      
  • Set values for config.activeadmin_associations.autocomplete_models in your config/application.rb. This should be a list of the models that you have added autocomplete statements to:

    `config.activeadmin_associations.autocomplete_models = %w(post user tag)`
    

If you plan to use other autocomplete JS libraries there are 2 other configs you may want to look at:

Different libraries send different param names for the query to the autocomplete endpoint you give it. For instance, jquery.tokeninput uses the q parameter while jQueryUI uses the term parameter. If no setting is given we will just use the q parameter. To configure this you need a statement like this in your config/application.rb:

config.activeadmin_associations.autocomplete_query_term_param_names = [:q, :term]

It might happen that the hash the autocomplete ActiveRecord macro provides for individual results won't play nice with the JS autocomplete plugin you're using. In this case we provide a way to format individual results yourself. Just assign an object that responds to call (like a proc) to config.activeadmin_associations.autocomplete_result_formatter in your config/application.rb like so:

config.activeadmin_associations.autocomplete_result_formatter = proc { |record, autocomplete_attribute, autocomplete_options|
  {:name => record.send(autocomplete_attribute), :id => record.id,
    :another_value => record.send(autocomplete_options[:other_value_method])}
}

Other Configuration

We add functionality so that when you do a destroy action you are redirected back to the Referer or the ActiveAdmin Dashboard. If you'd like to remove this functionality you can just put this in your config/application.rb:

config.activeadmin_associations.destroy_redirect = false

Setup your admin resource definitions

The main thing this Rails Engine provides is a way to easily configure simple forms that handle has_many relationships better then how ActiveAdmin does out of the box. Since we don't override any core ActiveAdmin functionality you can include this in resources you want to use it on and not on others.

Here's how you get started:

Add association_actions somewhere inside your ActiveAdmin resource definition block:

ActiveAdmin.register Post do
  association_actions
  # ...
end

You then also need to tell it you want to use the form template bundled with this Engine:

ActiveAdmin.register Post do
  association_actions
  
  form :partial => "admin/shared/form"
  # ...
end

Now you need to define the columns and the has_many relationships:

ActiveAdmin.register Post do
  association_actions
  
  form :partial => "admin/shared/form"
  
  form_columns :title, :body, :slug, :author, :published_at, :featured
  
  form_associations do
    association :tags, [:name, :post_count]
    association :revisions do
      fields :version_number, :created_at, :update_at
    end
  end
end

Defining the columns you want to edit in your form:

Pass to the form_columns method a list of column that there should be inputs for on the form.

Defining associations to manage at the bottom of edit pages:

The form_associations is used to define the associations you want to manage at the bottom of the edit pages. This method takes a block that is used to define these associations and the columns to display.

If you use the associations method inside the block then you can define multiple associations at once:

form_associations do
  association :tags, :revisions
end

In this case all the content_columns for the models will be used as the columns in the association tables. This is probably good for getting started quickly but you'll probably find you quickly outgrow it.

You can use individual association method calls and pass the list of attributes/methods to use as columns in the table:

form_associations do
  association :tags, [:name, :post_count]
end

You can also define the columns inside a block passed to the association method with a call to the fields method:

form_associations do
  association :revisions do
    fields :version_number, :created_at, :update_at
  end
end

Or if you prefer you can use multiple calls to the field method:

form_associations do
  association :revisions do
    field :version_number
    field :created_at
    field :update_at
  end
end

You are also free to mix and match:

form_associations do
  association :revisions, [:version_number] do
    fields :created_at, :another_column
    field :update_at
  end
end

Fine grained control over the form:

If you want more control over the main part of the form you can define a active_association_form which takes a block with 1 parameter (which is the form object):

ActiveAdmin.register Post do
  association_actions
  
  form :partial => "admin/shared/form"
  
  active_association_form do |f|
    f.inputs do
      f.input :title
      f.input :body
      f.input :slug, :label => "This is the value that will be used in the URL bar for the post."
    end
    f.inputs do
      f.input :author, :as => :select
      f.input :published_at
    end
  end
  
  form_associations do
    association :tags, [:name, :post_count]
    association :revisions do
      fields :version_number, :created_at, :update_at
    end
  end
end

Overriding the templates

If this still doesn't give you the power you're looking for you can override any of the partial templates this engine uses.

  • admin/shared/_form.html.erb – you probably don't want to override this one instead you probably want to use your own _form.html.erb template in your app/views/admin/RESOURCE_NAME directory and have this in your AA resource config: form :partial => 'form'. But if you really want to change how all the activeadmin_associations forms look you can.
  • admin/shared/_collection_tabe.html.erb – this is how we generate the tables for the has_many relationships below the form. Once again not something I'd recommend editing.
  • admin/shared/_association_collection_table_actions.html.erb – this defines the actions that you can do on each related record. The default is "edit" and "unrelate". You may want to override this for instance to define different actions for different models.
  • admin/shared/_add_to_association.html.erb – This is the form to relate existing records to the parent record.

Contributing to ActiveAdmin Associations

  • Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
  • Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
  • Fork the project.
  • Start a feature/bugfix branch.
  • Commit and push until you are happy with your contribution.
  • Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright

Copyright (c) 2012 Brian Landau (Viget). See MIT_LICENSE.txt for further details.

More Repositories

1

blendid

A delicious blend of gulp tasks combined into a configurable asset pipeline and static site builder
JavaScript
4,986
star
2

gulp-rails-pipeline

Ditch the Rails Asset Pipeline and roll your own with Gulp
Ruby
646
star
3

Twitter-Bootstrap-for-Omnigraffle

Omnigraffle stencil, template, and color picker modeled after Twitter Bootstrap
585
star
4

microcosm

Flux with actions at center stage. Write optimistic updates, cancel requests, and track changes with ease.
JavaScript
487
star
5

react-ink

A React component for adding material design style ink
JavaScript
325
star
6

colonel-kurtz

A Block Editor
JavaScript
318
star
7

sass-json-vars

Import variables as JSON into Sass
Ruby
294
star
8

grunt-complexity

A JavaScript complexity analysis grunt task.
JavaScript
221
star
9

sprig

Relational seeding for Rails apps
Ruby
208
star
10

jmapping

jQuery plugin for creating Google Maps from semantic markup
JavaScript
207
star
11

olive_branch

Handle camel/snake/dash case conversion
Ruby
180
star
12

acts_as_markup

Represent ActiveRecord Markdown, Textile, or RDoc columns as Markdown, Textile, or RDoc objects using various external libraries to convert to HTML.
Ruby
123
star
13

whitespace-tmbundle

TextMate bundle to remove trailing whitespace & tabs
115
star
14

capistrano_rsync_with_remote_cache

A deployment strategy for Capistrano 2.0 which combines rsync with a remote cache, allowing fast deployments from SCM servers behind firewalls.
Ruby
102
star
15

serialize_with_options

Simple XML and JSON APIs for your Rails app
Ruby
92
star
16

cachebar

A simple API caching layer built on top of HTTParty and Redis
Ruby
88
star
17

redirector

A Rails engine that adds a piece of middleware to the top of your middleware stack that looks for redirect rules stored in your database and redirects you accordingly.
Ruby
83
star
18

react-focus-trap

Traps focus for accessible dropdowns and modal content
JavaScript
81
star
19

stat_board

Simple dashboard of records created this week, this month, and all time, mountable as a Rails Engine.
Ruby
79
star
20

ensure-animation

Ensure animation runs until class loaded
JavaScript
76
star
21

nav_lynx

Rails helper to generate navigation links with a selected class.
Ruby
75
star
22

simplest_auth

Simple implementation of authentication for Rails
Ruby
73
star
23

tailwindcss-plugins

A collection of plugins for Tailwind CSS
JavaScript
58
star
24

interactive-wcag

A filterable and shareable version of the WCAG 2.0 spec.
46
star
25

storyboard

For making ADVENTURES
TypeScript
43
star
26

jquery.transport

Transport elements to other containers based upon media queries.
JavaScript
42
star
27

ruby-string-showdown

Double vs Single Quoted Ruby Strings... Which will emerge victorious??
Ruby
39
star
28

trackomatic

A high-performance tracking enhancement for Google Analytics.
JavaScript
34
star
29

an-isomorphic-chart

Charts are for everyone. A pending blog post.
JavaScript
33
star
30

otp

One-time pad programming exercise
Ruby
31
star
31

ruby_spark

Ruby Gem to make API calls to the Spark Cloud
Ruby
31
star
32

ars-arsenal

A react gallery picker
TypeScript
30
star
33

json-weight

Measure the weight of a JSON endpoint
JavaScript
30
star
34

augmented-card

Example project for ARKit Image Tracking blog post
Swift
29
star
35

simplest_status

Simple status functionality for Rails models.
Ruby
28
star
36

craft-color-swatches

PHP
27
star
37

ca11y

A lightweight accessible dependency-free datepicker
JavaScript
26
star
38

watch-dog

Monit + Sinatra + Monk + SQLite + Mustache = multi-site dowtime alert app
Ruby
25
star
39

jambells

HQ/Boulder Pointless Weekend Project
Elixir
25
star
40

craft-localeredirector

Craft plugin for detecting user language preferences and redirecting to the appropriate locale.
PHP
24
star
41

craft-videoembed

Craft plugin to generate an embed URL from a YouTube or Vimeo URL.
PHP
24
star
42

ffeud

Elixir
23
star
43

platomformio

Integration Atom IDE with PlatformIO
CoffeeScript
23
star
44

jest-with-nightmare

JavaScript
22
star
45

craft-profile

A command-line utility for capturing Craft CMS Profiling output and reporting averages.
JavaScript
22
star
46

sprig-reap

Sprig-Reap is a gem that allows you to output your application's data state to seed files.
Ruby
18
star
47

Screenless

A $55 alternative user interface for rapidly prototyping ideas
C++
16
star
48

foliage

A light, cursor-like tree data structure
JavaScript
15
star
49

canvas-instagram-filters

Demo for an upcoming blog post
JavaScript
15
star
50

simple-benchmark

A simple gem to benchmark spots in your Ruby / Rails code
Ruby
14
star
51

Material-Design-for-Omnigraffle

Omnigraffle stencil modeled after the Material Design sticker sheets
14
star
52

gangway

A client-side API abstraction layer
JavaScript
13
star
53

pointless-feedback

Rails Engine to handle basic user feedback
Ruby
13
star
54

craft-classnames

Craft plugin for conditionally joining css class names together in Twig templates. Really helps with wrangling Tailwind CSS.
PHP
11
star
55

is-it-viget

A demo app for viget.com tutorial
Swift
11
star
56

beginning-react-native

The online home of the SXSW 2016 Beginning iOS Development With React Native Workshop
11
star
57

special-delivery

A webhook event manager for Mailgun
Ruby
10
star
58

d3-builder

Builds D3 as a browserify dependency
JavaScript
10
star
59

checkoning

Visualizating team PR interactions
JavaScript
10
star
60

react-dragon

A very simple drag and drop component. Did I mention it was simple?
JavaScript
10
star
61

diode

An extremely small, single event emitter
JavaScript
9
star
62

prestotype

(WIP) Simple UX prototype boilerplate
JavaScript
9
star
63

craft-site-starter

PHP
8
star
64

craft-viget-base

PHP
7
star
65

slack_alert

A simple button that lights up, plays jingles, and interacts with Slack.
Ruby
7
star
66

rails_polymorphic_select

This is a simple Rails extension that allows you to create polymorphic select inputs for relationships that are polymorphic. It takes advantage of Rails 4.2 Global ID
Ruby
7
star
67

chronolog

Change Tracking for ActiveAdmin
Ruby
7
star
68

sxsw

SXSW Connected Devices Workshop Materials
Arduino
6
star
69

grunt-git-hooks-demo

A sample application to get started using Git hooks with Grunt.
JavaScript
6
star
70

trailbuddy-view-transition

Astro
6
star
71

reword

A tiny translator.
JavaScript
6
star
72

active_versioning

Plug-and-Play Versioning for Rails
Ruby
6
star
73

craft-sidebartoggle

Add the ability to hide the meta sidebar on element entry screens
PHP
5
star
74

gradebook

Example application for the Rails Developer position
5
star
75

VL-Date-Selects

EE plugin to dynamically generated selects for months, days, and years.
PHP
5
star
76

gastropod

Simple library for generating slugs
Ruby
5
star
77

talking-heads

The creepy talking head app.
JavaScript
5
star
78

bode

The bode webserver, written in C
C
5
star
79

washi

A simple, backbone inspired view helper.
JavaScript
5
star
80

microcosm-preact

Microcosm bindings for Preact:
4
star
81

romanize

Roman numeral conversion programming exercise
Ruby
4
star
82

Search-Words

Ruby
4
star
83

inline-svg-sprite

Inlines external svgs sprites and updates `xlink:href` attributes in `<use>` tags to reference the inlined svg.
JavaScript
4
star
84

Style-and-Swatch-Palettes

4
star
85

microcosm-devtools

Developer tools for Microcosm
3
star
86

lights-out

New programming challenge based a game from the 80s
Ruby
3
star
87

VL_CP_Logger

ExpressionEngine extension that logs more actions to the control panel log.
PHP
3
star
88

dnsimple

Python module for interacting with DNSimple service
Python
3
star
89

Device-Asset-Templates

3
star
90

duke-colab-course

Arduino
3
star
91

json-feed-validator

HTML
3
star
92

responsive-page-text

Mixins for LESS and Sass to make all page text β€”font sizes and line heightsβ€” responsive
CSS
3
star
93

webpack-intro

Intro to Webpacks in Steps
JavaScript
3
star
94

elixir-deploy-quickstart

Quickstart docs and files to get an Elixir app running on production
Elixir
3
star
95

lights-out-vr

A WebVR exploration of Lights Out.
JavaScript
3
star
96

snakey-table-ios

πŸ“± Custom UITableViewCells in iOS
Swift
3
star
97

microcosm-debugger

No longer in service. Use https://github.com/vigetlabs/microcosm-devtools
JavaScript
2
star
98

stimulus-controllers

Astro
2
star
99

gather-content-api

PHP Client for GatherContent API
PHP
2
star
100

wordpress-site-starter

JavaScript
2
star