实施的标记系统中的错误 [英] Bug in implemented tagging system

查看:74
本文介绍了实施的标记系统中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经遵循Hartl的教程来制作带有标签系统的ToDoList,也借助此



之后



这是插入<$后我命令行上的更新日志c $ c>放入 MicropostsController#index 中的params.inspect ,然后依次单击tag1和tag2。

 在2019-01-25 23:37:01 +0800开始为127.0.0.1获取GET / tags / tag1,由MicropostsController#index作为HTML处理
参数:{ tag => tag1}
用户负载(0.7ms)选择 users。* FROM users WHERE users。 id =? LIMIT? [[ id,2],[ LIMIT,1]]
标签加载(0.1ms)选择标签。*从标签到标签。名称 =? LIMIT? [[[ name, tag1],[ LIMIT,1]]
< ActionController :: Parameters { controller => microposts, action => index,允许使用 tag => tag1}:false>
在布局/应用程序中渲染microposts / index.html.erb
Micropost加载(0.6毫秒)选择 microposts。*从 microposts中的 microposts中。 user_id =? ORDER BY microposts。 created_at DESC [[ user_id,2]]
标签加载(0.6毫秒)选择标签。 id = taggings。 tag_id在 taggings。 micropost_id =吗? [[ micropost_id,20]]
标签加载(0.1ms)选择标签。*从标签内联接标签到标签。 id =标签。 tag_id在哪里标签。 micropost_id =? [[ micropost_id,14]]
标签加载(0.1ms)选择标签。*从标签内联接标签到标签。 id =标签。 tag_id在哪里标签。 micropost_id =? [[ micropost_id,8]]
标签加载(0.1ms)选择标签。*从标签内联接标签到标签。 id =标签。 tag_id在哪里标签。 micropost_id =? [[ micropost_id,2]]
在布局/应用程序中渲染的microposts / index.html.erb(15.8ms)
渲染的布局/_rails_default.html.erb(82.8ms)
渲染的layouts / _shim.html.erb(0.3ms)
渲染的layouts / _header.html.erb(1.2ms)
渲染的layouts / _footer.html.erb(1.7ms)
已完成200 OK in 157ms(Views:116.8ms | ActiveRecord:10.4ms)


在2019-01-25 23:37:16 +0800开始获取GET / tags / tag2为127.0.0.1
由MicropostsController#index以HTML
的形式处理
参数:{ tag => tag2}
用户负载(0.1ms)选择 users。* FROM users WHERE users。 id =? LIMIT? [[ id,2],[ LIMIT,1]]
标签加载(0.6ms)选择标签。*从标签到标签。名称 =? LIMIT? [[ name, tag2],[ LIMIT,1]]
< ActionController :: Parameters { controller => microposts, action => index,允许使用 tag => tag2}:false>
在布局/应用程序中渲染microposts / index.html.erb
Micropost加载(0.2毫秒)选择 microposts。*从 microposts中找到 microposts。 user_id =? ORDER BY microposts。 created_at DESC [[ user_id,2]]
标签加载(0.1ms)选择 tags。*从 tags内部联接 taggings到 tags。 id = taggings。 tag_id在 taggings。 micropost_id =吗? [[ micropost_id,20]]
标签加载(0.1ms)选择标签。*从标签内联接标签到标签。 id =标签。 tag_id在哪里标签。 micropost_id =? [[ micropost_id,14]]
标签加载(0.1ms)选择标签。*从标签内联接标签到标签。 id =标签。 tag_id在哪里标签。 micropost_id =? [[ micropost_id,8]]
标签加载(0.1ms)选择标签。*从标签内联接标签到标签。 id =标签。 tag_id在哪里标签。 micropost_id =? [[ micropost_id,2]]
在布局/应用程序中渲染的microposts / index.html.erb(9.6ms)
渲染的布局/_rails_default.html.erb(65.7ms)
渲染的layouts / _shim.html.erb(0.3ms)
渲染的layouts / _header.html.erb(1.1ms)
渲染的layouts / _footer.html.erb(1.5ms)
已完成200 OK在104毫秒内(观看次数:95.9ms | ActiveRecord:1.4毫秒)

这是我的控制器代码:



MicropostsController

  class MicropostsController< ApplicationController 
before_action:logged_in_user,仅:[:index,:show,:create,:destroy]
before_action:correct_user,仅::destroy


def索引
@microposts = current_user.microposts
@microposts = @ microposts.tagged_with(params [:tag])if params [:tag]
end


def show
@micropost = Micropost.find(params [:id])
end


def create
@micropost = current_user.microposts。如果@ micropost.save
flash [:success] =创建了Micropost!,则build(micropost_params)

redirect_to root_url
其他
@feed_items = []
渲染 static_pages / home
结束
结束

def破坏
@ micropost.destroy
flash [:success] =您已删除任务!
redirect_to request.referrer || root_url
结束

私人

def micropost_params
params.require(:micropost).permit(:content,:tag_list,:tag,
{tag_ids:[]},:tag_ids)
结束

defcorrect_user
@micropost = current_user.microposts.find_by(id:params [:id])
redirect_to root_url如果@ micropost.nil吗?
结束
结束

SessionsController

  class SessionsController< ApplicationController 

def新
结束

def创建
@user = User.find_by(电子邮件:params [:session] [:email] .downcase )
if(@user&& @ user.authenticate(params [:session] [:password]))
log_in @user
flash [:success] =欢迎回来, #{@用户名}!
params [:session] [:remember_me] ==‘1’吗?记住(@user):忘记(@user)
redirect_back_or或root_path
其他
flash.now [:danger] ='无效的电子邮件/密码组合'
呈现'new'
结束
结束

def销毁
log_out是否已登录?
redirect_to root_url
结束
结束

StaticPagesController

  class StaticPagesController<如果已登录,ApplicationController 
def home

@new_micropost = Micropost.new
@feed_items = current_user.microposts.paginate(page:params [:page])
结束
结束

def帮助
结束

def大约
结束

def联络
结束
结束

UsersController

  class UsersController< ApplicationController 
before_action:logged_in_user,仅:[:edit,:update,:destroy]
before_action:correct_user,仅:[:edit,:update]
before_action:admin_user,仅:[:破坏]


def show
@user = User.find(params [:id])
@microposts = @ user.microposts.paginate(页面:params [:page])
结束

def新
@user = User.new
结束

def索引
@ users = User.paginate(page:params [:page])
end


def create
@user = User.new(user_params)
如果@ user.save
log_in @user
flash [:info] =欢迎使用待办事项,#{@ user.name}
redirect_to @user
否则
呈现'new'
end
end

def admin
@users = User.paginate(page:params [:page])
end

def destroy
a = User.find(params [:id])。name
User.find(params [:id])。destroy
flash [:success] =#{a}具有已被删除!
redirect_to users_url
end

def admin_user
redirect_to(root_url)除非current_user.admin?
结束

def编辑
@user = User.find(params [:id])
结束

def更新
@user = User.find(params [:id])
如果@ user.update_attributes(user_params)
flash [:success] = @ user.name的配置文件已更新
redirect_to(@user)
其他
flash [:danger] =更新失败。
render'edit'
end
end

private
def user_params
params.require(:user).permit(:name, :email,:password,
:password_confirmation,:admin)
end
def logging_in_user
除非login_in?
store_location
flash [:danger] =您尚未登录。请登录。
redirect_to login_url
结束
结束

defcorrect_user
@user = User.find(params [:id])
如果!current_user ?(@ user)
flash [:danger] =您无权访问此页面。
redirect_to(root_url)
结束
结束
结束

microposts / index.html.erb

 < h1>过滤的微型帖子页面< / h1> 
< div class = col-md-8 offset-2>
<%@ microposts.each做| micropost | %>
< p><%=截断(micropost.content,长度:50)%< / p
< p>< small>标签:<%=原始micropost.tags.map(&:name).map {| t | link_to t,tag_path(t)} .join(’,’)%>< / small< / p>
< span class = timestamp>
发表<%= time_ago_in_words(micropost.created_at)%>前。
<%,如果current_user?(micropost.user)%>
<%=链接到完成,micropost_path(micropost),方法::删除,数据:{确认:继续努力! }%>
<%end%>
< / span>
<%end%>
< / div>

Micropost模型

  class Micropost< ApplicationRecord 
属于:user
has_many:taggings
has_many:tags,通过::taggings,:dependent => :delete_all
default_scope-> {order(created_at::desc)}
验证:user_id,状态:true
验证:content,状态:true,长度:{最大:140}
attr_accessor:tag_list



def self.tagged_with(name)
Tag.find_by!(name:name).microposts
end

def self。 tag_counts
Tag.select('tags。*,count(taggings.tag_id)as count')
.joins(:taggings).group('taggings.tag_id')
结束

def tag_list
tags.map(&:name).join(',')
end

def tag_list =(names)
self.tags = names.split(',')。map do | n |
Tag.where(name:n.strip).first_or_create!
结束
结束
结束

Config / routes.rb和运行耙路

  Rails.application.routes.draw do 
资源:用户
资源:微博

获得 / about,至: static_pages#about
获得 / contact,至: static_pages#contact
获取'/ signup',发送至:'users#new'
post'/ signup',发送至:'users#create'
get'/ login',发送至:'sessions#new '
发布'/ login',至:'sessions#create'
删除'/ logout',至:'sessions#destroy'
get'/ users / admin',至:' users#admin'

得到'tags /:tag',到:'microposts#index',as::tag

root'static_pages#home'
结束

前缀动词URI模式控制器#操作
用户GET /users(.:format)users#index
POST /users(.:format)users#create
new_user GET /users/new(.:format)users#new
edit_user GET /users/:id/edit(.:format)users#edit
user GET /users/:id(.:format)users #show
PATCH /users/:id(.:format)用户#update
PUT /users/:id(.:format)users#update
DELETE / users /:id(。 :format)用户#destroy
microposts GET /microposts(.:format)microposts#index
POST /microposts(.:format)microposts#create
new_micropost GET / microposts / new(.:格式)microposts#new
edit_micropost GET /microposts/:id/edit(.:format)microposts#edit
micropost GET /microposts/:id(.:format)microposts#show
PATCH /microposts/:id(.:format)microposts#update
PUT /microposts/:id(.:format)microposts#update
DELETE /microposts/:id(.:format)microposts#destroy
关于GET /about(.:format)static_pages#about
contact GET /contact(.:format)static_pages#contact
注册GET /signup(.:format)users#new
POST / signup(。:format)用户#创建
登录GET /login(.:format)会话#new
POST /login(.:format)会话#create
注销DELETE / logout(。 :format)会话#destroy
users_admin GET /users/admin(.:format)users#admin
标签GET /tags/:tag(.:format)microposts#index
root GET / static_pages#home

更新:



它似乎在 rails控制台上运行时, tagged_with 方法没有过滤,而是比较所有微博和应该是的微博。由 tagged_with 过滤。

  irb(main):004:0> User.first.microposts 
用户负载(0.3毫秒)选择用户。*从用户排序由用户。 id ASC限制? [[ LIMIT,1]]
Micropost加载(0.2ms)选择 microposts。*从 microposts到 microposts。 user_id =? ORDER BY microposts。 created_at DESC LIMIT? [[ user_id,1],[ LIMIT,11]]
=> #< ActiveRecord :: Associations :: CollectionProxy [#< Micropost ID:55,内容: Magnam nulla labour quibusdam veniam dolores。,user_id:1,created_at: 2019-01-23 14:39:21, Updated_at: 2019-01-23 14:39:21> ;,#< Micropost id:49,内容: Et non enim perspiciatis perferendis esse necessit ...,user_id:1,1,created_at: 2019-01 -23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID:43,内容: Ducimus voluptatum esse qui iusto quamag magnam,user_id:1 ,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID:37,内容: Adipisci iusto sed facilis molestiae。 ,user_id:1,created_at: 2019-01-23 14:39:21,updatedat: 2019-01-23 14:39:21>,#< Micropost ID:31,内容: Ipsam ,用户ID:1,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID :25,内容: Qui et non hic maiores et commodi labourum aut quib ...,用户ID:1,created_at : 2019-01-23 14:39:21,updatedat: 2019-01-23 14:39:21>,#< Micropost ID:19,内容: Itaque velit ut unde dolorem in。 ,user_id:1,created_at: 2019-01-23 14:39:21,updatedat: 2019-01-23 14:39:21>,#< Micropost ID:13,内容: Repellendus architecto rerum commodi dolorem。,用户ID:1,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID:7,内容: UtAccusantium dolor voluptas quisquam laboriosam ...,用户ID:1,created_at: 2019-01-23 14:39:21,updatedat: 2019-01-23 14:39:21> ;, #< Micropost ID:1,内容:坐在办公室的非商品。,用户ID:1,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39: 21>]>
irb(main):005:0> User.first.microposts.tagged_with( tag2)
用户负载(0.3ms)选择 users。*从 users排序由 users。 id ASC LIMIT? [[ LIMIT,1]]
标签加载(0.2ms)选择标签。*从标签到标签。名称 =? LIMIT? [[[ name, tag2],[ LIMIT,1]]
Micropost加载(0.5ms)选择 microposts。*从 microposts内部联接 tags到 microposts。 id = taggings。 micropost_id在 taggings中。 tag_id =吗? ORDER BY microposts。 created_at DESC LIMIT? [[ tag_id,4],[ LIMIT,11]]
=> #< ActiveRecord :: Associations :: CollectionProxy [#< Micropost ID:57,内容: Magnam nulla labour quibusdam veniam dolores。,user_id:3,created_at: 2019-01-23 14:39:21, Updated_at: 2019-01-23 14:39:21> ;,#< Micropost ID:54,内容: Et non enim perspiciatis perferendis esse necessit ...,user_id:6,6,created_at: 2019-01 -23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID:51,内容: Et non enim perspiciatis perferendis esse necessit ...,user_id :3,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID:49,内容: Et non enim perspiciatis perferendis esse necessit ...,用户ID:1,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID: 48,内容: Ducimus voluptatum esse qui iusto quamag magnam。,user_id:6,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21> ,#< Micropost ID:46,内容: Ducimus voluptatum esse qui iusto quamag magnam。,user_i d:4,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID:45,内容: Ducimus voluptatum esse qui iusto quamag magnam。,用户ID:3,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21>,#< Micropost ID:43 ,内容: Ducimus voluptatum esse qui iusto quamag magnam。,user_id:1,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39:21> ;, #< Micropost ID:42,内容: Adipisci iusto sed facilis molestiae。,user_id:6,created_at: 2019-01-23 14:39:21,updated_at: 2019-01-23 14:39: 21>,#< Micropost ID:40,内容: Adipisci iusto sed facilis molestiae。,user_id:4,created_at: 2019-01-23 14:39:21,updated_at: 2019-01- 23 14:39:21> ;, ...]>

是否有人知道标记系统如何工作以及如何解决问题?如果需要更多信息,请告诉我。

解决方案

如果我理解正确,当您单击列表中的特定标签时,您应该被重定向到包含所有包含单击标记的所有帖子的过滤的微型帖子页面页面。



从您的角度来看, microposts / index.html.erb 会将用户发送到 tag_path ,因此这就是所有逻辑的起点。



基于三元运算符,您拥有 MicroPostController#index ,这意味着您的参数[:标签] 为零,并且您正在列出所有帖子。



您能否请Stdout params.inspect



欢呼声


I have followed Hartl's tutorial to make a ToDoList with a tagging system, also with the help of this word guide and video. However, I do not really understand how the tagging system works in terms of the filtering, so I just copied it and improvised.

Now I have a problem with my filtering system as now it just redirects to a brand new page that contains all tasks including those that doesn't have the clicked tag.

Before

After

Here is the updated log on my command line after inserting puts params.inspect in the MicropostsController#index, then clicking tag1 then tag2.

Started GET "/tags/tag1" for 127.0.0.1 at 2019-01-25 23:37:01 +0800
Processing by MicropostsController#index as HTML
  Parameters: {"tag"=>"tag1"}
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  Tag Load (0.1ms)  SELECT  "tags".* FROM "tags" WHERE "tags"."name" = ? LIMIT ?  [["name", "tag1"], ["LIMIT", 1]]
<ActionController::Parameters {"controller"=>"microposts", "action"=>"index", "tag"=>"tag1"} permitted: false>
  Rendering microposts/index.html.erb within layouts/application
  Micropost Load (0.6ms)  SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? ORDER BY "microposts"."created_at" DESC  [["user_id", 2]]
  Tag Load (0.6ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."micropost_id" = ?  [["micropost_id", 20]]
  Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."micropost_id" = ?  [["micropost_id", 14]]
  Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."micropost_id" = ?  [["micropost_id", 8]]
  Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."micropost_id" = ?  [["micropost_id", 2]]
  Rendered microposts/index.html.erb within layouts/application (15.8ms)
  Rendered layouts/_rails_default.html.erb (82.8ms)
  Rendered layouts/_shim.html.erb (0.3ms)
  Rendered layouts/_header.html.erb (1.2ms)
  Rendered layouts/_footer.html.erb (1.7ms)
Completed 200 OK in 157ms (Views: 116.8ms | ActiveRecord: 10.4ms)


Started GET "/tags/tag2" for 127.0.0.1 at 2019-01-25 23:37:16 +0800
Processing by MicropostsController#index as HTML
  Parameters: {"tag"=>"tag2"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  Tag Load (0.6ms)  SELECT  "tags".* FROM "tags" WHERE "tags"."name" = ? LIMIT ?  [["name", "tag2"], ["LIMIT", 1]]
<ActionController::Parameters {"controller"=>"microposts", "action"=>"index", "tag"=>"tag2"} permitted: false>
  Rendering microposts/index.html.erb within layouts/application
  Micropost Load (0.2ms)  SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? ORDER BY "microposts"."created_at" DESC  [["user_id", 2]]
  Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."micropost_id" = ?  [["micropost_id", 20]]
  Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."micropost_id" = ?  [["micropost_id", 14]]
  Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."micropost_id" = ?  [["micropost_id", 8]]
  Tag Load (0.1ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."micropost_id" = ?  [["micropost_id", 2]]
  Rendered microposts/index.html.erb within layouts/application (9.6ms)
  Rendered layouts/_rails_default.html.erb (65.7ms)
  Rendered layouts/_shim.html.erb (0.3ms)
  Rendered layouts/_header.html.erb (1.1ms)
  Rendered layouts/_footer.html.erb (1.5ms)
Completed 200 OK in 104ms (Views: 95.9ms | ActiveRecord: 1.4ms)

Here's my controller code:

MicropostsController

class MicropostsController < ApplicationController
  before_action :logged_in_user, only: [:index, :show, :create, :destroy]
  before_action :correct_user,   only: :destroy


  def index
    @microposts = current_user.microposts
    @microposts = @microposts.tagged_with(params[:tag]) if params[:tag]
  end


  def show
    @micropost = Micropost.find(params[:id])
  end


  def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

  def destroy
    @micropost.destroy
    flash[:success] = "You have deleted a task!"
    redirect_to request.referrer || root_url
  end

  private

    def micropost_params
      params.require(:micropost).permit(:content, :tag_list, :tag, 
        {tag_ids: [] }, :tag_ids)
    end

    def correct_user
      @micropost = current_user.microposts.find_by(id: params[:id])
      redirect_to root_url if @micropost.nil?
    end
end

SessionsController

class SessionsController < ApplicationController

  def new
  end

  def create
    @user = User.find_by(email: params[:session][:email].downcase)
    if (@user && @user.authenticate(params[:session][:password]))
      log_in @user
      flash[:success] = "Welcome back, #{@user.name}!"
      params[:session][:remember_me] == '1' ? remember(@user) : forget(@user)
      redirect_back_or root_path
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
    log_out if logged_in?
    redirect_to root_url
  end
end

StaticPagesController

class StaticPagesController < ApplicationController
  def home
    if logged_in?
      @new_micropost = Micropost.new
      @feed_items = current_user.microposts.paginate(page: params[:page]) 
    end 
  end

  def help
  end

  def about
  end

  def contact
  end
end

UsersController

class UsersController < ApplicationController
  before_action :logged_in_user, only: [:edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: [:destroy]


  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
  end

  def new
    @user = User.new
  end

  def index
    @users = User.paginate(page: params[:page])
  end


  def create
   @user = User.new(user_params)
   if @user.save
     log_in @user
     flash[:info] = "Welcome to the to-do app, #{@user.name}"
     redirect_to @user
   else
     render 'new'
   end
  end

  def admin
    @users = User.paginate(page: params[:page])
  end

  def destroy
    a = User.find(params[:id]).name
    User.find(params[:id]).destroy
    flash[:success] = "#{a} has been deleted!"
    redirect_to users_url
  end

  def admin_user
    redirect_to(root_url) unless current_user.admin?
  end

 def edit
   @user = User.find(params[:id])
 end

 def update
  @user = User.find(params[:id])
  if @user.update_attributes(user_params)
    flash[:success] = "Profile for @user.name has been updated"
    redirect_to(@user)
  else
    flash[:danger] = "Update Failed."
    render 'edit'
  end
end

  private
    def user_params
      params.require(:user).permit(:name, :email, :password,
                                  :password_confirmation, :admin)
    end
    def logged_in_user
      unless logged_in?
        store_location
        flash[:danger] = "You are not logged in. Please log in."
        redirect_to login_url
      end
    end

    def correct_user
      @user = User.find(params[:id])
      if !current_user?(@user)
        flash[:danger] = "You are not authorized to visit this page."
        redirect_to(root_url)
      end
    end
  end

microposts/index.html.erb

<h1>Filtered Micropost Page</h1>
<div class = "col-md-8 offset-2">
  <% @microposts.each do |micropost| %>
    <p><%= truncate(micropost.content, length: 50) %></p>
    <p><small>Tags: <%= raw micropost.tags.map(&:name).map { |t| link_to t, tag_path(t) }.join(', ') %></small</p>
        <span class="timestamp">
            Posted <%= time_ago_in_words(micropost.created_at) %> ago.
            <% if current_user?(micropost.user) %>
              <%= link_to "Done", micropost_path(micropost), method: :delete, data: { confirm: "Keep up the good work!" } %>
            <% end %>
        </span>
    <% end %>
</div>

Micropost Model

class Micropost < ApplicationRecord
  belongs_to :user
  has_many :taggings
  has_many :tags, through: :taggings, :dependent => :delete_all
  default_scope -> { order(created_at: :desc) }
  validates :user_id, presence: true
  validates :content, presence: true, length: {maximum: 140 }
  attr_accessor :tag_list



  def self.tagged_with(name)
    Tag.find_by!(name: name).microposts
  end

  def self.tag_counts
    Tag.select('tags.*, count(taggings.tag_id) as count')
    .joins(:taggings).group('taggings.tag_id')
  end

  def tag_list
    tags.map(&:name).join(', ')
  end

  def tag_list=(names)
    self.tags = names.split(',').map do |n|
      Tag.where(name: n.strip).first_or_create!
    end
  end
end

Config/routes.rb and running rake routes

Rails.application.routes.draw do
  resources :users
  resources :microposts          

  get    '/about',   to: 'static_pages#about'
  get    '/contact', to: 'static_pages#contact'
  get    '/signup',  to: 'users#new'
  post    '/signup',  to: 'users#create'
  get    '/login',    to: 'sessions#new'
  post   '/login',    to: 'sessions#create'
  delete '/logout',   to: 'sessions#destroy'
  get   '/users/admin',     to: 'users#admin'

  get 'tags/:tag', to: 'microposts#index', as: :tag

  root   'static_pages#home'
end

        Prefix Verb   URI Pattern                    Controller#Action
         users GET    /users(.:format)               users#index
               POST   /users(.:format)               users#create
      new_user GET    /users/new(.:format)           users#new
     edit_user GET    /users/:id/edit(.:format)      users#edit
          user GET    /users/:id(.:format)           users#show
               PATCH  /users/:id(.:format)           users#update
               PUT    /users/:id(.:format)           users#update
               DELETE /users/:id(.:format)           users#destroy
    microposts GET    /microposts(.:format)          microposts#index
               POST   /microposts(.:format)          microposts#create
 new_micropost GET    /microposts/new(.:format)      microposts#new
edit_micropost GET    /microposts/:id/edit(.:format) microposts#edit
     micropost GET    /microposts/:id(.:format)      microposts#show
               PATCH  /microposts/:id(.:format)      microposts#update
               PUT    /microposts/:id(.:format)      microposts#update
               DELETE /microposts/:id(.:format)      microposts#destroy
         about GET    /about(.:format)               static_pages#about
       contact GET    /contact(.:format)             static_pages#contact
        signup GET    /signup(.:format)              users#new
               POST   /signup(.:format)              users#create
         login GET    /login(.:format)               sessions#new
               POST   /login(.:format)               sessions#create
        logout DELETE /logout(.:format)              sessions#destroy
   users_admin GET    /users/admin(.:format)         users#admin
           tag GET    /tags/:tag(.:format)           microposts#index
          root GET    /                              static_pages#home

Update:

It seems that running on rails console, the tagged_with method isn't filtering, comparing all microposts and what is supposed to be filtered by tagged_with.

irb(main):004:0> User.first.microposts
  User Load (0.3ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Micropost Load (0.2ms)  SELECT  "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? ORDER BY "microposts"."created_at" DESC LIMIT ?  [["user_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Micropost id: 55, content: "Magnam nulla labore quibusdam veniam dolores.", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 49, content: "Et non enim perspiciatis perferendis esse necessit...", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 43, content: "Ducimus voluptatum esse qui iusto quasi magnam.", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 37, content: "Adipisci iusto sed facilis molestiae.", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 31, content: "Ipsam aliquid cum natus eos corrupti inventore.", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 25, content: "Qui et non hic maiores et commodi laborum aut quib...", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 19, content: "Itaque velit ut unde dolorem in.", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 13, content: "Repellendus architecto rerum commodi dolorem.", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 7, content: "Ut accusantium dolor voluptas quisquam laboriosam ...", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 1, content: "Officiis non commodi at sit.", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">]>
irb(main):005:0> User.first.microposts.tagged_with("tag2")
  User Load (0.3ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Tag Load (0.2ms)  SELECT  "tags".* FROM "tags" WHERE "tags"."name" = ? LIMIT ?  [["name", "tag2"], ["LIMIT", 1]]
  Micropost Load (0.5ms)  SELECT  "microposts".* FROM "microposts" INNER JOIN "taggings" ON "microposts"."id" = "taggings"."micropost_id" WHERE "taggings"."tag_id" = ? ORDER BY "microposts"."created_at" DESC LIMIT ?  [["tag_id", 4], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Micropost id: 57, content: "Magnam nulla labore quibusdam veniam dolores.", user_id: 3, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 54, content: "Et non enim perspiciatis perferendis esse necessit...", user_id: 6, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 51, content: "Et non enim perspiciatis perferendis esse necessit...", user_id: 3, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 49, content: "Et non enim perspiciatis perferendis esse necessit...", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 48, content: "Ducimus voluptatum esse qui iusto quasi magnam.", user_id: 6, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 46, content: "Ducimus voluptatum esse qui iusto quasi magnam.", user_id: 4, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 45, content: "Ducimus voluptatum esse qui iusto quasi magnam.", user_id: 3, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 43, content: "Ducimus voluptatum esse qui iusto quasi magnam.", user_id: 1, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 42, content: "Adipisci iusto sed facilis molestiae.", user_id: 6, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, #<Micropost id: 40, content: "Adipisci iusto sed facilis molestiae.", user_id: 4, created_at: "2019-01-23 14:39:21", updated_at: "2019-01-23 14:39:21">, ...]>

Does anyone have any clue how the tagging system works and how to solve the problem? Do inform me if more information is needed. Thanks a lot in advance.

解决方案

If I understood correctly, when you click the particular tag in the list you supposed to be redirected to the page "Filtered Micropost Page" that contains all posts that include clicked tag.

From your view, microposts/index.html.erb you're sending user to tag_path so that's where all logic starts.

Based on ternary operator you hav on MicroPostController#index that means your params[:tag] is nil and you're listing all posts.

Could you please Stdout params.inspect

Cheers

这篇关于实施的标记系统中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆