If I used this code to set up a tagging system for my app, how would I then render the posts with the tags I assigned to them. For instance if I assigned a sports tag to a couple posts, how would I then render all posts with the sports tag assigned to it
rails g model tag name:string
rails g model tagging article_id:integer tag_id:integer
rake db:migrate
class Tagging < ActiveRecord::Base
belongs_to :article
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :articles, :through => :taggings
end
class Article < ActiveRecord::Base
has_many :comments, :dependent => :destroy
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
validates_presence_of :name, :content
attr_writer :tag_names
after_save :assign_tags
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
private
def assign_tags
if @tag_names
self.tags = @tag_names.split(/\s+/).map do |name|
Tag.find_or_create_by_name(name)
end
end
end
end
<p>
<%= f.label :tag_names %><br />
<%= f.text_field :tag_names %>
</p>
Maybe something like this: