【问题标题】:rendering post with assigned tag使用分配的标签呈现帖子
【发布时间】:2012-06-04 07:57:17
【问题描述】:

如果我使用此代码为我的应用程序设置标签系统,那么我将如何使用我分配给它们的标签来呈现帖子。例如,如果我为几个帖子分配了一个运动标签,那么我将如何渲染所有带有分配给它的运动标签的帖子

 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>

【问题讨论】:

  • 答案不是tag.articles吗?
  • 这会呈现带有特定标签的帖子吗?
  • 与@Chris Mohr 的回答类似,它会呈现带有“sports”标签的帖子。 Rails 会根据has_many :through 自动构建正确的 SQL。您可以检查开发日志中生成的 sql :)

标签: ruby-on-rails ruby ruby-on-rails-3 tags render


【解决方案1】:

可能是这样的:

# TagsController
def show
  @articles = Tag.find_by_name('sports').articles
end

# tags/show.html.haml
- @articles.each do |article|
  = render :partial => :article

【讨论】:

  • 如果标签不止一个,例如体育和政治等,该怎么办?
  • 您可能会在 show 方法中使用 tag.id。 @articles = Tag.find(params[:id]).articles 链接到标签:tag_url(tag)
  • 在视图中会是
  • 视图将与答案中的相同。要从另一个视图链接到标签的显示操作,您可以使用像 tag_url(tag) 这样的 url 助手,其中 tag 是一个标签实例。 url 看起来像yourserver.com/tags/12,其中12 是标签ID。
  • 视图中的另一种选择是将集合传递给部分喜欢:render :partial=&gt; article, :collection =&gt; @articles
猜你喜欢
  • 2013-05-23
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2017-02-25
  • 2012-06-19
  • 2016-04-05
相关资源
最近更新 更多