find_or_initialize_by_title uniqueness

时间:2012-11-08 11:01:52

标签: ruby-on-rails ruby-on-rails-3 activerecord associations

我有一个嵌套形式的标签的text_field(它与Trips相关联),在保存时用逗号分隔,并用逗号分隔的字符串中保存单词。我已经通过一些箍来实现它,并且它正在发生,就像我现在想要的那样。唯一的缺点是它似乎没有使当前标签成为唯一标签(如果它存在将现有标签与新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

提前致谢!

0 个答案:

没有答案