0

的標籤仍然存在:如何在更新時使標籤持續存在?在

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

惡是before_save :set_tag_owner,您已設置self.tag_list = nil。 因此,在保存目標之前,您的標籤列表被清空。

它在更新操作中工作,因爲您正在重新設置標籤。

要解決此問題,請僅在要刪除標記時將nil分配給tag_list。

+1

寫回調是依賴於其他類,模型不是一個好的做法。所以你可以在控制器中分配'self.tag_list = nil',或者你可以編寫一個服務類來更新目標並在那裏寫。 –

+0

也許你沒有在目標對象上調用它,在更新之前嘗試@ goal.tag_list = nil。不要對不起'是人類'。 –

+0

@ AnthonyGalli.com我無法打開你的問題。可能你已經解決了你自己的問題,並刪除了問題。 –

相關問題