change routes of update rails

208 Views Asked by At

I have a doubt in changing a route value. I have this situation:

routes.rb

  patch 'supplies/update'
  get 'supplies/edit'
  get 'supplies/index'


views/supplies/edit.html.erb

    <%= form_for @supply , :url => supplies_update_path(id: @supply) do |f| %>

    ....

i would use in the edit.html.erb file the following code:

<%= form_for @supply do |f| %>

what i have to change in the route to obtain the correct supply_path for this form_for?

thank you.

EDIT:

enter image description here

class SuppliesController < ApplicationController
    before_action :set_supply, only: [:show, :edit, :update, :destroy]

    load_and_authorize_resource


    # GET /supplies/index
  def index
            @supplies = Supply.includes(:product).all
  end

    def edit
  end

    # PATCH/PUT /supplies/1
  def update
    respond_to do |format|
      if @supply.update(supply_params)
        format.html { redirect_to supplies_index_path, notice: 'Quantità Aggiornata.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @supply.errors, status: :unprocessable_entity }
      end
    end
  end

   private


  def set_supply
      @supply = Supply.includes(:product).find(params[:id])
        rescue ActiveRecord::RecordNotFound
            render :template => 'public/404.html'
    end


  def supply_params
    params.require(:supply).permit(:quantity)
  end



end
1

There are 1 best solutions below

4
On BEST ANSWER

You can simply use <%= form_for @supply do |f| %> for edit.html.erb file. Reason is: When you instantiate @supply in edit method in SuppliesController, Rails will automatically post the form to update method, you do not need to tell it explicitly. Same way, in new.html.erb, you will also use the same: <%= form_for @supply do |f| %>, but now in your new method, you will do @supply = Supply.new, Rails will post this form to create method.

You do need to define routes, but as far as correct path is concerned, Rails will take care of it as long as you provide correct @supply variable in form_for.


Edit:

In your routes file:

resources :supplies