Created
September 12, 2012 21:35
-
-
Save halfdan/3710093 to your computer and use it in GitHub Desktop.
Taggable Post model in Rails 3.2.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tag < ActiveRecord::Base | |
attr_accessible :name | |
has_many :taggings | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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