def insert_at(position = 1)
      list_class.transaction do
        ids = lock_list!
        position = [[1, position].max, ids.size].min

        if persisted?
          current_position = ids.index(id) + 1

          sql = <<-SQL
            #{quoted_position_column} = CASE
            WHEN #{quoted_position_column} = #{current_position} THEN #{position}
            WHEN #{quoted_position_column} > #{current_position}
            AND #{quoted_position_column} <= #{position} THEN #{quoted_position_column} - 1
            WHEN #{quoted_position_column} < #{current_position}
            AND #{quoted_position_column} >= #{position} THEN #{quoted_position_column} + 1
            ELSE #{quoted_position_column}
            END
          SQL

          list_scope.update_all(sql)
          update_position(position)
        else
          save!

          sql = <<-SQL
            #{quoted_position_column} = CASE
            WHEN #{quoted_position_column} >= #{position} THEN #{quoted_position_column} + 1
            ELSE #{quoted_position_column}
            END
          SQL

          list_scope.update_all(sql)
          update_position(position)
        end
      end
    end
def insert_at(position = 1)
      list_class.transaction do
        ids = lock_list!
        position = [[1, position].max, ids.size].min

        if persisted?
          current_position = ids.index(id) + 1

          sql = <<-SQL
            #{quoted_position_column} = CASE
            WHEN #{quoted_position_column} = #{current_position} THEN #{position}
            WHEN #{quoted_position_column} > #{current_position}
            AND #{quoted_position_column} <= #{position} THEN #{quoted_position_column} - 1
            WHEN #{quoted_position_column} < #{current_position}
            AND #{quoted_position_column} >= #{position} THEN #{quoted_position_column} + 1
            ELSE #{quoted_position_column}
            END
          SQL

          list_scope.update_all(sql)
          update_position(position)
        else
          save!

          sql = <<-SQL
            #{quoted_position_column} = CASE
            WHEN #{quoted_position_column} >= #{position} THEN #{quoted_position_column} + 1
            ELSE #{quoted_position_column}
            END
          SQL

          list_scope.update_all(sql)
          update_position(position)
        end
      end
    end
Insert the item at the given position (defaults to the top position of 1).