更新时如何使标签保持不变?

时间:2015-09-05 20:29:51

标签: ruby-on-rails ruby model-view-controller tags acts-as-taggable-on

标签在以下期间持续存在:

  def update
    if @goal.update(goal_params)
      respond_modal_with @goal, location: root_path
    else
      render action: 'edit'
    end
  end

但是当我通过以下方式更新目标时:

  def mark_accomplished
    @goal.update(accomplished: true)

      respond_to do |format|
        format.html
        format.js { render :nothing => true }
      end
  end

当用户点击mark_accomplished按钮时,该目标的标记就会消失:

<%= link_to 'Accomplished', mark_accomplished_path(goal), remote: true, method: 'put',  %>

路线:

get '/goal_signup/', to: 'goals#goal_signup', as: 'goal_signup'

它与标签(gem 'acts-as-taggable-on')有关,因为在我的习惯MVC的类似情况下会出现这个问题。我在这里使用目标作为主要示例,但如果您希望习惯也提供更多背景,请告诉我。

goal.rb

 class Goal < ActiveRecord::Base
    scope :publish, ->{ where(:conceal => false) }
    belongs_to :user
    acts_as_taggable
    scope :accomplished, -> { where(accomplished: true) }
    scope :unaccomplished, -> { where(accomplished: nil) }
    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
      self.tag_list = nil
    end
end

TagsController

class TagsController < ApplicationController
  def index
    @tags = ActsAsTaggableOn::Tag.most_used(20)
    # The tags for all users and habits.
    @special_tags = ActsAsTaggableOn::Tag.includes(:taggings)
                                         .where('taggings.taggable_type' => ['Habit','User','Valuation','Goal'])
                                         .most_used(10)
    # to get tags where the current user is the tagger
    @user_tags = current_user.owned_tags
  end

  def show
    @tag = ActsAsTaggableOn::Tag.find(params[:id])
  end
end

分贝

  create_table "taggings", force: true do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context",       limit: 128
    t.datetime "created_at"
  end

  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true, using: :btree
  add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context", using: :btree

  create_table "tags", force: true do |t|
    t.string  "name"
    t.integer "taggings_count", default: 0
  end

  add_index "tags", ["name"], name: "index_tags_on_name", unique: true, using: :btree

1 个答案:

答案 0 :(得分:1)

邪恶是before_save :set_tag_owner,你设置了self.tag_list = nil。 因此,在保存目标之前,您的标记列表会被清空。

它正在进行更新操作,因为您再次设置标记。

要解决此问题,请仅在您要删除标记时将nil指定给tag_list。