如果我使用此代码为我的应用程序设置标记系统,那么我将如何使用我分配给它们的标记来呈现帖子。例如,如果我为一对帖子分配了一个体育标签,那么我将如何呈现分配给它的体育标签的所有帖子
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>
答案 0 :(得分:1)
也许是这样的:
# TagsController
def show
@articles = Tag.find_by_name('sports').articles
end
# tags/show.html.haml
- @articles.each do |article|
= render :partial => :article