When working with ownership the taggable model gets its tags a little different. Without ownership it can get its tags like so:
@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
However, both of these opperations create taggins
, whose tagger_id
and tagger_type
are nil
.
In order to have these fields set, you have to use this method:
@user.tag(@photo, on: :tags, with: 'a tag')
Suppose you add this line to the create/update
actions of your PhotosController
:
@user.tag(@photo, on: :tags, with: params[:photo][:tag_list])
This will create two taggings (one with and one without tagger_id/_type
), because params[:photo][:tag_list]
is already included in photo_params
. So in order to avoid that, just do not whitelist :tag_list
.
For Rails 3 - remove :tag_list
from attr_accessible
.
For Rails 4 - remove :tag_list
from params.require(:photo).permit(:tag_list)
.
At the end your create
action might look like this:
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
Also note that when tagging objects this way you cannot use the usual tag_list
method to retrieve the tags of a photo, because it searches for taggings
, where tagger_id IS NULL
. You have to use instead
@photo.tags_from(@user)
In case your taggable object belongs_to
a single user you can also user all_tags_list
.