title: Redirect to edit page automatically if record exists
body: <p>I want to create a new record if it not exist. Otherwise, redirect to edit page automatically.</p>
  
  <p>In case the record exists (e.g: <code>@sale</code> is not <code>nil</code>). However, I got error message:</p>
  
  <blockquote>
    <p>app/views/sales/_form.html.erb where line #1 raised:</p>
    
    <p>First argument in form cannot contain nil or be empty</p>
  </blockquote>
  
  <p>Please show place where I had mistake.</p>
  
  <p>sales_controller.rb</p>
  
  <pre><code>  def new
      @sale = Sale.find_on_today
      if @sale.nil?
        @sale = Sale.new
      else
        redirect_to edit_sale_path(@sale)
      end
    end
  
    def edit
    end
  
    # POST /sales
    def create
      Kpi.transaction do
        @sale = Sale.new(sale_params)
        @sale.user_id = current_user.id
        respond_to do |format|
          if @sale.save
            format.html { redirect_to sales_path, notice: 'Sale was successfully created.' }
          else
            format.html { render :new }
          end
        end
      end
    end
  
    # PATCH/PUT /sales/1
    def update
      respond_to do |format|
        if @sale.update(sale_params)
          format.html { redirect_to sales_path, notice: 'Sale was successfully updated.' }
        else
          format.html { render :edit }
        end
      end
    end
  
    private
    def sale_params
      params.require(:sale).permit(:sale_money, :no_of_items)
    end
  </code></pre>
  
  <p>_form.html.erb</p>
  
  <pre><code>&lt;%= form_for @sale do |f| %&gt;
    &lt;label for="sale_money"&gt;&lt;%= t('.sale_money_label')%&gt;&lt;/label&gt;
    &lt;%= f.text_field :sale_money, class: "form-control" %&gt;
  
    &lt;label for="no_of_items"&gt;&lt;%= t('.no_of_items_label')%&gt;&lt;/label&gt;
    &lt;%= f.text_field :sale_amount, class: "form-control" %&gt;
  
    &lt;%= f.submit t('.btn_submit'), class: 'btn btn-primary' %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>UPDATE: Based on fylooi's answer, I forget redirect is a new request, so <code>@sale</code> is <code>nil</code>. I change method <code>new</code>, <code>edit</code> and <code>update</code> in controller, it is working</p>
  
  <p>sales_controller.rb</p>
  
  <pre><code>def new
      @sale = Sale.find_on_today
      if @sale.nil?
          @sale = Sale.new
      else
          redirect_to edit_sale_path(@sale.id)
      end
  end
  
  def edit
      @sale = Sale.find(params[:id])
  end
  
  def update
      @sale = Sale.find(params[:id])
      respond_to do |format|
        if @sale.update(kpi_params)
          format.html { redirect_to kpis_path, notice: 'Sale was successfully updated.' }
        else
          format.html { render :edit }
        end
      end
  end
  </code></pre>
  
  <p>edit.html.erb</p>
  
  <pre><code>&lt;%= render partial: 'form' %&gt;
  </code></pre>