Мне нужно разрешить пользователям выбирать теги для своих сообщений, но из закрытого списка (скажем, только админ может добавлять новые теги или они предопределены другим способом). Каждый пост может иметь много тегов, поэтому он должен быть мультиселектором. К сожалению, после добавления меток select2-rails не удалось сохранить в БД. Как я могу это исправить? This не работает для меня.Как использовать select2-rails с act_as_taggable_on (simple_form)
PostsController:
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
application.js:
$(document).ready(function(){
$('.tags').select2({
placeholder: 'Click to select',
theme: 'bootstrap'
});
});
что такое label_method и как это отличается от value_method? Благодарю. –
@TimmyVonHeiss label_method - это то, что вы показываете в селекторе, value_method - это то, что вы передаете для сохранения в db. , например. если у вас есть категории, а сообщения имеют category_id в db, вы хотите показать название категории в селекторе и идентификатор категории пропуска на db - вы устанавливаете label_method как: name (название категории) и value_method как: id (идентификатор категории). – weezing