Skip to content

Instantly share code, notes, and snippets.

@ottodranik
Last active February 6, 2017 09:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ottodranik/684dd46f14030b9069d3 to your computer and use it in GitHub Desktop.
Save ottodranik/684dd46f14030b9069d3 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
@lgurmendez
Copy link

I have a custom id field in my tagging table, which makes reference to other model. Im having some trouble when saving the tags, i dont know where to save this custom field. I try making an observer like in the example above but its just not working.

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)
puts "AAAAAAA"

end
end

my file name for this observer is call tagging_observer.rb under the model directory. I have install the 'rails-observers' gem, what am i missing??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment