我有一个嵌套形式的标签文本字段(它与旅行相关联),它在保存时以逗号分隔,并将单词保存在由逗号分隔的字符串中。我已经跳过了一些障碍来实现它,现在它正在按照我的意愿发生。唯一的缺点是它似乎不会使当前标签成为唯一标签(如果存在,则将现有标签与新的 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
提前致谢!