我正在尝试在文章的显示页面上显示相关文章。当用户查看任何特定文章时,数据库中的所有相关文章都应根据标签显示在该页面(右侧栏中)上(因为每篇文章至少有一个标签)。我的应用程序在标签和文章之间有关系(请见下文) .
文章控制器.rb
class ArticlesController < ApplicationController
before_filter :is_user_admin, only: [:new, :create, :edit, :destroy]
def is_user_admin
redirect_to(action: :index) unless current_user.try(:is_admin?)
return false
end
def index
@articles = Article.all(:order => "created_at DESC")
@article_titles = Article.first(10)
@tags = Tag.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.new(params[:article])
@article.user_id = current_user.id
if @article.save
flash[:success] = "article created!"
redirect_to article_path(@article)
else
render 'new'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to action: 'index'
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article])
flash.notice = "Article '#{@article.title}' Updated!"
redirect_to article_path(@article)
else
render 'edit'
end
end
end
tags_controller.rb
class TagsController < ApplicationController
#before_filter :user_signed_in, only: [:destroy]
def index
@tags = Tag.all
end
def show
@tag = Tag.find(params[:id])
end
end
架构.rb
ActiveRecord::Schema.define(:version => 20130411074056) do
create_table "articles", :force => true do |t|
t.string "title"
t.text "body"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "user_id"
end
create_table "comments", :force => true do |t|
t.text "content"
t.integer "user_id"
t.string "article_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "article_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "taggings", ["article_id"], :name => "index_taggings_on_article_id"
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
create_table "tags", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
article/show.html.erb :- 当用户根据标签查看任何特定文章时,我需要在其中显示相关文章
目前,articles/show.html.erb 页面具有标签(S)名称,我想在 db 中显示所有具有相同标签的文章以显示在此页面上(右侧栏)。任何想法如何实现此关系以获取相关文章以及在何处编写此逻辑以及如何在视图中实现。