Update owner tags via form

前端 未结 7 1825
Happy的楠姐
Happy的楠姐 2020-12-18 01:26

I would like to uniquely use owner tags in my app. My problem is that when I create / update a post via a form I only have f.text_field :tag_list which only upd

7条回答
  •  感情败类
    2020-12-18 02:04

    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.

提交回复
热议问题