如何获得标签工作行为
我是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
您可以从终端 '耙路线',看你所有的路径。在这里你的标签指向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你的代码(不要重复你自己);它可以节省您在文章#标记的操作中对代码重复的需求,这将使您更容易理解和维护代码库。
希望有所帮助。
感谢您的意见。事情仍然不起作用,但我正在阅读路线以及如何编写适当的方法。希望我能尽快把它们结合在一起。干杯。 – Schipperius 2012-07-17 01:59:45
请为您的路线文件 – 2012-07-08 03:25:10
添加一个片段,为什么您的索引中有@article = Article.new? – 2012-07-08 03:27:06
编辑:添加路线片段和删除** @ article = Article.new **从控制器中的** def index **(不记得它为什么在那里,我一直在复制/粘贴和制造误会...... ) – Schipperius 2012-07-10 01:56:07