当使用所有权时,可标记模型的标签会有所不同。如果没有所有权,它可以像这样获得它的标签:
@photo.tag_list << 'a tag' # adds a tag to the existing list
@photo.tag_list = 'a tag' # sets 'a tag' to be the tag of the @post
但是,这两个操作都创建taggins
, whotagger_id
和tagger_type
are nil
。
为了设置这些字段,您必须使用此方法:
@user.tag(@photo, on: :tags, with: 'a tag')
假设您将此行添加到create/update
您的操作中PhotosController
:
@user.tag(@photo, on: :tags, with: params[:photo][:tag_list])
这将创建两个标记(一个带有,一个不带tagger_id/_type
),因为params[:photo][:tag_list]
已经包含在photo_params
. 因此,为了避免这种情况,请不要将其列入白名单:tag_list
。
对于 Rails 3 -:tag_list
从attr_accessible
.
对于 Rails 4 -:tag_list
从params.require(:photo).permit(:tag_list)
.
最后,您的create
操作可能如下所示:
def create
@photo = Photo.new(photo_params) # at this point @photo will not have any tags, because :tag_list is not whitelisted
current_user.tag(@photo, on: :tags, with: params[:photo][:tag_list])
if @photo.save
redirect_to @photo
else
render :new
end
end
另请注意,以这种方式标记对象时,您不能使用通常的tag_list
方法来检索照片的标签,因为它会搜索taggings
, where tagger_id IS NULL
。你必须改用
@photo.tags_from(@user)
如果您的可标记对象belongs_to
是单个用户,您也可以使用 user all_tags_list
。