Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Taggable Post model in Rails 3.2.x

View post.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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
View post.rb
1 2 3 4 5
class Tag < ActiveRecord::Base
attr_accessible :name
 
has_many :taggings
end
View post.rb
1 2 3 4 5 6
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
Something went wrong with that request. Please try again.