保存時にコンマで分割され、コンマで区切られた文字列に単語を保存する、ネストされた形式(トリップに関連付けられている)のタグのtext_fieldがあります。私はそれを実現するためにいくつかのフープを飛び越えましたが、今では私が望むように起こっています. 唯一の欠点は、現在のタグを一意のタグにしないように見えることです (存在する場合は、新しいタグを作成する代わりに、既存のタグを新しい Trip に関連付けます)。
タグを個別に分割して保存するコードは次のとおりです。
if params[:trip][:tags_attributes].present?
params[:trip][:tags_attributes].each do |tag|
@a = tag[1]['title']
@a.split(',').each do |single|
@trip.tags.find_or_initialize_by_title(single)
end
end
end
念のため、Trip.rb:
class Trip < ActiveRecord::Base
attr_accessible :description, :title, :user_id,
:triplocations_attributes, :photo, :category_ids,
:start_city, :tripphotos_attributes, :img_url, :thumb_url, :images,
:tags_attributes, :province
# validates :title, :length => {:minimum => 3}
# validates :description, :presence => true
# validates_associated :tags
has_many :triplocations, :dependent => :destroy
has_many :tripphotos, :dependent => :destroy
has_and_belongs_to_many :categories
has_and_belongs_to_many :tags
accepts_nested_attributes_for :triplocations, allow_destroy: true
accepts_nested_attributes_for :tripphotos, allow_destroy: true
accepts_nested_attributes_for :categories
accepts_nested_attributes_for :tags
end
前もって感謝します!