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

后端 未结 7 1486
悲哀的现实
悲哀的现实 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:09

    You want to use the magic method find_or_create_by

    def check_exists
        tag = Tag.find_or_create_by_name_and_user_id(:name => self.name, :user_id => current_user.id)
    end
    

    Check out the ActiveRecord::Base docs for more info

提交回复
热议问题