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

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

    try this

      def check_exists
        tag = Tag.where(:name => self.name, :user_id => current_user.id).first
        tag = Tag.new({:name => self.name, :user_id => current_user.id}) unless tag
      end
    

    use Tag.new instead of Tag.create

提交回复
热议问题