Skip to content

Instantly share code, notes, and snippets.

@halfdan
Created September 12, 2012 21:35
Show Gist options
  • Save halfdan/3710093 to your computer and use it in GitHub Desktop.
Save halfdan/3710093 to your computer and use it in GitHub Desktop.
Taggable Post model in Rails 3.2.x
class Post < ActiveRecord::Base
attr_accessible :body, :title, :tag_names
attr_reader :tag_names
has_many :taggings
has_many :tags, :through => :taggings
def tag_names=(tag_list)
tag_names = tag_list.gsub(/\s+/, "").split(",")
existing = self.tags.map {|t| t.name }
(existing - tag_names).each do |name|
self.tags.delete Tag.find_by_name(name)
end
tag_names.each do |name|
self.tags << Tag.find_or_create_by_name(name)
end
end
end
class Tag < ActiveRecord::Base
attr_accessible :name
has_many :taggings
end
class Tagging < ActiveRecord::Base
attr_accessible :post_id, :tag_id
belongs_to :tag, :counter_cache => true, touch: true
belongs_to :post
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment