2012-03-15 64 views
-1

我有一個型號:把用戶帶到一個頁面,顯示所有標有他點擊的標籤(Rails)的帖子?

class Post < ActiveRecord::Base  
    belongs_to :user 

    has_many :taggings, :dependent => :destroy 
    has_many :tags, :through => :taggings 

    attr_writer :tag_names 
    after_save :assign_tags 
    before_create :init_sort_column 

    def tag_names 
    @tag_names || tags.map(&:name).join(" ") 
    end 

    private 

    def assign_tags 
    self.tags = [] 
    return if @tag_names.blank? 
    @tag_names.split(" ").each do |name| 
     tag = Tag.find_or_create_by_name(name) 
     self.tags << tag unless tags.include?(tag) 
    end 
    end 
end 

標籤型號:

class Tag < ActiveRecord::Base 
    has_many :taggings, :dependent => :destroy 
    has_many :posts, :through => :taggings 
    has_many :subscriptions 
    #has_many :subscribed_users, :source => :user, :through => :subscriptions 
end 

這是我列出標籤:

<div class="top-tags"> 
    <% @tags.each do |tag| %> 
    <span class="tag-name"><%= tag.name %></span> 
    <span class="tag-count"><%= tag.posts.count %></span> 
    <% end %> 
</div> 

我希望用戶被帶到一個頁面,顯示所有標有他點擊的標籤的帖子(如StackOverflow )。

如何做到這一點?

編輯

這是我已經試過:

def tagged 
    @tag = Tag.find_by_name(params[:tagged_as]) 
    @posts = @tag.posts.paginate 
    end 

我打算在視圖中顯示的職位稱爲tagged.html.erb

但現在我卡住了。我不知道如何將:tagged_aslink_to結合使用。

+0

[?你嘗試過什麼(http://mattgemmell.com/2008/12/08/what -have-you-tried /) – 2012-03-15 03:34:40

+0

@TobiasCohen請參閱mi **編輯**。 – alexchenco 2012-03-15 03:51:33

回答

1

您可以將它們作爲選項的相關路線的幫手,例如包括在鏈接附加參數:

<%= link_to tag.name, tagged_posts_path(:tagged_as => tag.name) %> 

如果您不能確定您有哪條路線助手,你可以運行rake routes將它們全部列出(列表中最左邊一列)。

如果您還沒有準備好,我建議你閱讀了Rails指南路線太:http://guides.rubyonrails.org/routing.html

相關問題