How to check if a record exists before creating a new one in rails3?

后端 未结 7 1422
悲哀的现实
悲哀的现实 2021-02-03 14:36

Heres what I\'m trying to accomplish:

  • I have a tagging system in place.
  • Tags are created, when Posts are created (posts has_many :tags, :through => :tag
7条回答
  •  深忆病人
    2021-02-03 15:12

    There's a find_or_create_by_ function built right in to Rails

    # No 'Summer' tag exists
    Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
    
    # Now the 'Summer' tag does exist
    Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
    

    http://api.rubyonrails.org/classes/ActiveRecord/Base.html (under Dynamic attribute-based finders)

提交回复
热议问题