Skip to content

Instantly share code, notes, and snippets.

@jcsky
Forked from ottodranik/admin-product.rb
Created April 5, 2016 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcsky/f5a5111c7b11d64b18413b171c8d28d5 to your computer and use it in GitHub Desktop.
Save jcsky/f5a5111c7b11d64b18413b171c8d28d5 to your computer and use it in GitHub Desktop.
Example: Use Acts-As-Taggable-On gem with Active-Admin and rails observers
ActiveAdmin.register Product do
permit_params :name, :category_id, :description, :text, :slug, :in_slider, :tag_ids => []
filter :category
filter :base_tags
filter :name
filter :text
filter :created_at
filter :updated_at
controller do
def find_resource
scoped_collection.friendly.find(params[:id])
end
end
form do |f|
f.inputs "Main info" do
f.input :category
f.input :name
f.input :description
f.input :text
f.input :in_slider, :label => "Product in slider on Main Page"
f.input :tags, # Show all tags AND checked already selected one (by relations through :tags - input must named :tags)
as: :select,
multiple: :true,
collection: ActsAsTaggableOn::Tag.select(:id, :name).all
end
f.actions
end
end
....
module MyApp
class Application < Rails::Application
config.active_record.observers = :product_observer, :tagging_observer
end
end
class Product < ActiveRecord::Base
# Using friendly_id
extend FriendlyId
friendly_id :name, use: :slugged
# Product belongs to Category. So tags have a :tagger_id and :tagger_type too, and should be saved through object of Category.
belongs_to :category
# Using acts_as_taggable_on gem
acts_as_taggable # Alias for acts_as_taggable_on :tags
acts_as_taggable_on :tags, :skills
# Renamed a new slug after change :name field
def should_generate_new_friendly_id?
slug.blank? || name_changed?
end
end
class TaggingObserver < ActiveRecord::Observer
observe ActsAsTaggableOn::Tagging
# Before save add :tagger_id using refs on the object witch 'taggable' and owner of this 'taggable'
def before_save(tagging)
tagging.tagger = tagging.taggable.category if (tagging.taggable.respond_to?(:category) and tagging.tagger != tagging.taggable.category)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment