我是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 :(得分:0)
您可以从终端运行'rake routes'来查看所有路径。这里你的标签指向articles_path,你将看到文章控制器中索引操作的路由(“articles#index”)
您可以在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
这叫做干你的代码(不要重复自己);它可以节省文章#tagged action中代码重复的需要,这将使您更容易理解和维护代码库。
希望有所帮助。