2012-07-08 145 views
0

我是Ruby on Rails(和編程)的新手,這可能是一個非常愚蠢的問題。我正在使用Rails 3.2並嘗試使用acts_as_taggable_on在文章上生成標籤,並將這些標籤顯示爲文章索引和顯示頁面作爲可點擊鏈接。如何獲得標籤工作行爲

我有標籤可點擊文章展示和索引頁面,但鏈接只是回到索引頁面,不根據標籤名稱進行排序。我搜索了互聯網,並將各種來源的代碼拼湊在一起,但我顯然錯過了一些東西。

任何幫助非常感謝,因爲我已經用盡了我看似有限的知識!謝謝。

以下是我有:

class ArticlesController < ApplicationController 
    def tagged 
     @articles = Article.all(:order => 'created_at DESC') 
     @tags = Article.tag_counts_on(:tags) 
     @tagged_articles = Article.tagged_with(params[:tags]) 
     respond_to do |format| 
      format.html # index.html.erb 
      format.json { render :json => @articles } 
     end 
     end 

    def index 
     @articles = Article.paginate :page => params[:page], :per_page => 3  
     @tags = Article.tag_counts_on(:tags) 
     respond_to do |format| 
      format.html # index.html.erb 
      format.json { render json: @articles } 
     end 
     end 

module ArticlesHelper 
    include ActsAsTaggableOn::TagsHelper 
end 

class Article < ActiveRecord::Base 
    acts_as_ordered_taggable 
    acts_as_ordered_taggable_on :tags, :location, :about 
    attr_accessible :tag_list 
    scope :by_join_date, order("created_at DESC") 
end 

article/index.html.erb 
<% tag_cloud(@tags, %w(tag1 tag2 tag3 tag4)) do |tag| %> 
<%= link_to tag.name, articles_path(:id => tag.name) %> 
<% end %> 

article/show.html.erb 
<%= raw @article.tags.map { |tag| link_to tag.name, articles_path(:tag_id => tag) }.join(" | ") %> 

的routes.rb文件片段

authenticated :user do 
    root :to => 'home#index' 
    end 

    devise_for :users 
    resources :users, :only => [:show, :index] 

    resources :images 
    resources :articles 
+0

請爲您的路線文件 – 2012-07-08 03:25:10

+0

添加一個片段,爲什麼您的索引中有@article = Article.new? – 2012-07-08 03:27:06

+0

編輯:添加路線片段和刪除** @ article = Article.new **從控制器中的** def index **(不記得它爲什麼在那裏,我一直在複製/粘貼和製造誤會...... ) – Schipperius 2012-07-10 01:56:07

回答

0

您可以從終端 '耙路線',看你所有的路徑。在這裏你的標籤指向articles_path,您將看到路線中的文章控制器中的索引操作(「文章#指數」)

你可以在你的routes.rb文件創建另一個途徑,是這樣的:

match 'articles/tags' => 'articles#tagged', :as => :tagged 

如果您希望它優先,請將其放在路由文件中的其他位置,並記住您始終可以在終端中運行'rake routes'以查看路由是如何解釋的。

看到http://guides.rubyonrails.org/routing.html#naming-routes更多信息(也許讀了整個事情)

另一個(可能更好)選擇是使用PARAMS到您想要的功能組合成索引操作,例如... /文章?標記=真。然後,您可以使用邏輯基於params [:tagged]在索引控制器中定義@articles變量。一個簡單的例子可能是

def index 
    if params[:tagged] 
     @articles = Article.all(:order => 'created_at DESC') 
    else 
     Article.paginate :page => params[:page], :per_page => 3 
    end 

    @tags = Article.tag_counts_on(:tags) 
    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @articles } 
    end 
    end 

這被稱爲DRYing你的代碼(不要重複你自己);它可以節省您在文章#標記的操作中對代碼重複的需求,這將使您更容易理解和維護代碼庫。

希望有所幫助。

+0

感謝您的意見。事情仍然不起作用,但我正在閱讀路線以及如何編寫適當的方法。希望我能儘快把它們結合在一起。乾杯。 – Schipperius 2012-07-17 01:59:45