0
1

More than 3 years have passed since last update.

[Ruby on rails]タグ付け機能③投稿編集時のタグの編集と削除 (with 記事の下書き保存)

Last updated at Posted at 2021-08-16

初めに

②までの実装だと、投稿編集時にタグの数を減らしたりすると、
エラーが出るかと思います。

コードについて

③の記事から、投稿の下書き機能も導入しているため、
少しコードが見にくくなっています。
下書き機能については、以下の記事で説明しています。

下書き保存ではタグの保存はしないようにしたいので、以下のコードでは、
if params[:post][:status]== "公開"か、そうじゃないか(下書き)で、
条件分岐しています。

コントローラー

post_controller.rb
def update
    # postのid持ってくる
    @post = Post.find(params[:id])
    # 入力されたタグを受け取る
    tag_list = params[:post][:name].split(',')
    # もしpostの情報が更新されたら
    if @post.update(post_params)
      if params[:post][:status]== "公開"
    # このpost_idに紐づいていたタグを@oldに入れる
        @old_relations=PostTag.where(post_id: @post.id)
    # それらを取り出し、消す。消し終わる
        @old_relations.each do |relation|
        relation.delete
        end  
         @post.save_tag(tag_list)
        redirect_to post_path(@post.id), notice: '更新完了しました:)'
      else redirect_to posts_path, notice: '下書きに登録しました。'
      end
    else
      render :edit
    end
  end

記事の編集では、その投稿についていたタグを一旦全て削除し、
再度タグを登録し直しています。
①のモデルでの記述を思い出してみて、この方法しか思いつきませんでした。

とても参考になった記事

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1