我正在使用act-as-taggable gem https://github.com/mbleigh/acts-as-taggable-on 和jQueryTokenInput插件,为我的图像模型添加标签。到目前为止,标签已创建并添加正常。我按照教程http://bloginius.com/blog/2013/12/31/how-integrate-acts-as-taggable-on-with-jquery-token-input-with-rails-3/进行了操作。 但是,现在我希望能够在创建标记时将标记的所有权赋予current_user。 就像在宝石中一样s github页面,我试过了
@some_user.owned_taggings
@some_user.owned_tags
没有令人满意的结果。我继续并在tags表中添加了user_id。是否有一个tags -troller与acts-as-taggable-on gem相关联,我可以使用before_save修改为标签设置user_id? 谢谢!
答案 0 :(得分:0)
致力于所有权的section of the acts-as-taggable-on README,有助于您完成模型的细节。
但是,我不认为所提供的方法是正确的 - 他们会将所有拥有的标签(由任何人拥有,即),应用于每个所有者<>项目关系。以下是我的表现:
DEFAULT_ACTSASTAGGABLEON_TYPE = :tag
module TagToOwner
extend ActiveSupport::Concern
private
def add_owned_tag(item, owner, tags_to_add, options = {})
own_tag(item, owner, arrayify(tags_to_add), "add", options)
end
def remove_owned_tag(item, owner, tags_to_add, options = {})
own_tag(item, owner, arrayify(tags_to_add), "subtract", options)
end
def own_tag(item, owner, tags_to_add, direction = "add", opts)
tag_type = (options[:tag_type] || DEFAULT_ACTSASTAGGABLEON_TYPE)
owned_tag_list = item.owner_tags_on(owner, tag_type).map(&:name)
if direction == "subtract"
owned_tag_list = owned_tag_list.reject{|n| n.in?(tags_to_add)}
else
owned_tag_list.push(*tags_to_add)
end
owner.tag(item, with: stringify(owned_tag_list), on: tag_type, skip_save: (options[:skip_save] || true))
end
def arrayify(tags_to_add)
return tags_to_add if tags_to_add.is_a?(Array)
tags_to_add.split(",")
end
def stringify(tag_list)
tag_list.inject('') { |memo, tag| memo += (tag + ',') }.chomp(",")
end
end
和
class MyModelController < ApplicationController
include TagToOwner
# ...
def create
@my_model = MyModel.new(my_model_params)
add_tags
# ...
end
# ...
def update
add_tags
# ...
end
private
def add_tags
return unless params[:tag_list] && "#{params[:tag_list]}".split(",").any?
return unless validate_ownership_logic # <- e.g. `current_user`
add_owned_tag(@my_model, current_user, params[:tag_list])
end
end
请注意,我已针对act-as-taggable-on和an issue提交了a corresponding pull request来更正其自述文件。