リストモデルがあります。リストにはタグが埋め込まれています(Mongoidを使用)。ユーザーがリストを作成するとき、テキストフィールドのコンマ区切りリストを介して関連タグを指定できます。
リストアソシエーションを介してタグを保存するにはどうすればよいですか?リストモデルのaccepts_nested_attributes_for:tagsを使用してそれを行うことはできますか、それともタグ文字列を前処理する必要がありますか?
これが私がこれまでに持っているものです。タグ文字列を処理し、分割して、リストの一部である埋め込みタグドキュメントに各タグを個別に保存するにはどうすればよいですか?
リストコントローラー:
class ListsController < ApplicationController
def new
@list = List.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @list }
end
end
def create
list_params = params[:list]
list_params[:user_id] = current_user.id
@list = List.new(list_params)
if @list.save
redirect_to @list, notice: 'List was successfully created.'
else
render action: "new"
end
end
end
リスト作成フォーム
= form_for @list do |f|
- if @list.errors.any?
#error_explanation
%h2= "#{pluralize(@list.errors.count, "error")} prohibited this list from being saved:"
%ul
- @list.errors.full_messages.each do |msg|
%li= msg
.field
= f.label :name
= f.text_field :name
.field
= f.label :description
= f.text_field :description
.field
= f.fields_for :tags do |t|
= t.label :tags
= t.text_field :name
.actions
= f.submit 'Save'
リストモデル
class List
include Mongoid::Document
include Mongoid::Timestamps
field :name
field :description
embeds_many :items
embeds_many :comments
embeds_many :tags
belongs_to :user
accepts_nested_attributes_for :tags
タグモデル
class Tag
include Mongoid::Document
field :name
has_one :list
end
Geoffの提案に基づいて編集する
リストコントローラーは最終的に見えました。
def create
tags = params[:tags][:name]
list = params[:list]
list[:user_id] = current_user.id
@list = List.new(list)
tags.gsub("\s","").split(",").each do |tag_name|
@list.tags.new(:name => tag_name)
end
if @list.save
redirect_to @list, notice: 'List was successfully created.'
else
render action: "new"
end
end