How to fix duplicate taggings?

前提是你 提交于 2020-02-01 08:23:55

问题


Users can submit tags for Habits, Goals, Values, and Stats.

When a user clicks on a tag in the tag_cloud he is redirected to the home page with all the instances of that tag, but for some reason the instances that fall under Habits are duplicating.

Any ideas on why this is?

pages_controller

@habits = current_user.habits.tagged_with(params[:tag])

habit.rb

class Habit < ActiveRecord::Base
  belongs_to :user
  acts_as_taggable
  before_save :set_tag_owner

  def set_tag_owner 
    # Set the owner of some tags based on the current tag_list
    set_owner_tag_list_on(self.user, :tags, self.tag_list)
    # Clear the list so we don't get duplicate taggings (hmmm what does this mean? I copied this code & comment from somewhere else)
    # self.tag_list = nil
  end

In views/home.html.erb: <%= render @habits %> in routes.rb: root 'pages#home'.

I tried to post only the relevant stuff, but here's the gist of it.


回答1:


Have you tried uncommenting th line:

self.tag_list = nil

I guess you copied it over from this source or the linked stackoverflow question ? In your code comments you asked what the following comment line is about:

Clear the list so we don't get duplicate taggings

I digged through the sources and found the method you are calling:

def set_owner_tag_list_on(owner, context, new_list)

So as the last parameter is called new_list, i guess the old list, that you hand in to the set_owner_tag_list_on method, is would set the same tags again. Therefore the old tag_list without the owner is set to nil there, as tag_list only seems to contain the tags without owner (according to the docs)

Although I don't really see the point of using this owned taggings after all, since you create new habits for every user and always filter by user. As far as I can tell the ownership feature of acts_as_taggable_on is only useful when you have one recource that is tagged by multiple users and you want to know who tagged what. In your case everyone has his own taggable resources.



来源:https://stackoverflow.com/questions/31643598/how-to-fix-duplicate-taggings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!