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

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

    The question I originally asked got pretty distorted by the end. So I'm separating it.

    People who are trying to do what I originally asked can try this:

     before_create :check_tag_exists
    
     private
    
     def check_tag_exists
         @tag = Tag.find_by_name_and_user_id(self.name, self.user_id)
         if @tag != nil
           #
         end
      end
    

    This will enable you to check if your record has already been created. Any further logic you can drop in that if statment.

    0 讨论(0)
提交回复
热议问题