2

ユーザーが投稿のタグを選択できるようにする必要がありますが、クローズド リストから選択できます (管理者のみが新しいタグを追加できるか、他の方法で事前定義されているとしましょう)。各投稿には多くのタグを付けることができるため、マルチセレクターにする必要があります。残念ながら、select2-rails タグを追加した後、DB に保存できませんでした。どうすれば修正できますか?これは私にはうまくいきません。

投稿コントローラー:

class PostsController < ApplicationController
  before_action :find_post, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]

  def index
    @posts = Post.page(params[:page]).per(10)
    @tags = ActsAsTaggableOn::Tag.all
  end

  def new
    @post = current_user.posts.new
    @tags = ActsAsTaggableOn::Tag.all
  end

  def create
    @post = current_user.posts.new(post_params)
    if @post.save
      redirect_to @post, notice: _('Post created')
    else
      render :new, notice: _('Something went wrong')
    end
  end

  def show
    @tags = ActsAsTaggableOn::Tag.all
  end

  def edit
    authorize @post
    @tags = ActsAsTaggableOn::Tag.all
  end

  def update
    if @post.update(post_params)
      redirect_to @post, notice: _('Post updated')
    else
      render :edit, notice: _('Something went wrong')
    end
  end

  def destroy
    authorize @post
    if @post.destroy
      redirect_to root_path, notice: _('Post deleted')
    else
      redirect_to @post, notice: _('Something went wrong')
    end
  end

  private

  def post_params
    params.require(:post).permit(:title, :header, :content, :tag_list)
  end

  def find_post
    @post = Post.friendly.find(params[:id])
  end
end

モデル:

class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :title, use: :slugged
  acts_as_ordered_taggable_on :tags

  belongs_to :user

  validates :title, :header, :content, presence: true
  validates :title, uniqueness: true
end

意見:

= simple_form_for @post do |f|
  = f.input :title
  = f.input :header
  = f.input :content, input_html: { rows: 10 }
  = f.input :tag_list, collection: @tags, input_html: { multiple: true, class: 'tags' }
  = f.submit 'Save', class: 'btn btn-warning'
= link_to _('Back'), :back

アプリケーション.js:

$(document).ready(function(){
  $('.tags').select2({
    placeholder: 'Click to select',
    theme: 'bootstrap'
  });
});
4

1 に答える 1

3

うーん、思ったよりずっと簡単でした。私がしなければならなかったのはtag_list、配列として許可することだけでした(ここここtag_list: []で説明されているように、デフォルトの構文:tag_listはDBにタグを保存しません)が、この変更だけが奇妙な動作を引き起こしました-名前の代わりにタグIDを保存します. 上記のリンクで言及されていない2番目のことは、セレクターのラベルと値のメソッドを明示的に定義することです(重要です。デフォルトでは、タグ名ではなくタグのIDを渡すため、同じ名前の新しいタグを作成します以前のタグの ID)。

コントローラーで:

def post_params
  params.require(:post).permit(:title, :header, :content, tag_list: [])
end

そしてビューで:

= simple_form_for @post do |f|
  = f.input :title
  = f.input :header
  = f.input :content, input_html: { rows: 10 }
  = f.input :tag_list, collection: @tags, value_method: :name, label_method: :name, input_html: { multiple: true, class: 'tags' }
  = f.submit 'Save', class: 'btn btn-warning'
= link_to _('Back'), :back
于 2016-04-09T18:53:31.153 に答える