vendredi 11 novembre 2016

Autoincrement postgre DB id field in RAILS

I am trying to make an autoincrement id field into a postgre DB in rails. I am trying to get the maximum id and then just add +1 and pass it down to create method. I am not quite sure what I am doing wrong, but if I have 4 projects and add the 5th one, that is getting id 5, but if I delete that one and try to add another one, that's getting id 6, not 5 again. Here is my code:

 # GET /admin/projects/new
  def new
    @project = Project.new
    @project.id = Project.maximum(:id).next.to_i

    respond_to do |format|
      format.html # new.html.erb
    end
  end

  # GET /admin/projects/1/edit
  def edit
    @project = Project.find(params[:id])
  end

  # POST /admin/projects
  def create
    @project = Project.create(params[:project])

    respond_to do |format|
      if @project.save
        format.html { redirect_to projects_path, notice: 'Project was successfully created.' }
      else
        format.html { render action: "new" }
      end
    end
  end

I tried to add @project.save to new, but as much as I understand, the .save should only be done in the create method. Any ideas will be kindly appreciated :D

Aucun commentaire:

Enregistrer un commentaire