icemax2k icemax2k - 1 month ago 7
Ruby Question

Routing with parameters not working on rails

I've been trying to figure this one out but I'm becoming desperate because I don't see why this isn't working.
Whatever I try, no route is matching my link and I get the following error:


Routing Error: uninitialized constant LineItemsController


My link looks like this:

<%= button_to 'Add to template', line_items_path(template_id: @template, position_id: position) %>


So the link being created is:


http://localhost:3000/line_items?position_id=2&template_id=1


routes.rb:

Rails.application.routes.draw do
resources :line_items
resources :templates
resources :positions


line_item_controller.rb

class LineItemsController < ApplicationController
before_action :set_line_item, only: [:show, :edit, :update, :destroy]

# GET /line_items
# GET /line_items.json
def index
@line_items = LineItem.all
end

# GET /line_items/1
# GET /line_items/1.json
def show
end

# GET /line_items/new
def new
@line_item = LineItem.new
end

# GET /line_items/1/edit
def edit
end

# POST /line_items
# POST /line_items.json
def create
position = Position.find(params[:position_id])
template = Template.find(params[:template_id])
@line_item = LineItem.new(position, template)

respond_to do |format|
if @line_item.save
format.html { redirect_to template_url}
format.js {@current_item = @line_item}
format.json { render action: 'show',
status: :created, location: @line_item }
else
format.html { render action: 'new' }
format.json { render json: @line_item.errors,
status: :unprocessable_entity }
end
end
end

# PATCH/PUT /line_items/1
# PATCH/PUT /line_items/1.json
def update
respond_to do |format|
if @line_item.update(line_item_params)
format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end

# DELETE /line_items/1
# DELETE /line_items/1.json
def destroy
@line_item.destroy
respond_to do |format|
format.html { redirect_to line_items_url }
format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_line_item
@line_item = LineItem.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
# def line_item_params
# params.require(:line_item).permit(:position_id, :template_id)
# end
#...
end


From my understanding, my link should send a POST request that should call the
create
action of the
line_item controller
, thereby matching the route
POST /line_items(.:format) line_items#create


Thanks for the help guys!

Answer

I think the issue is the filename of your controller:

line_item_controller.rb should be line_items_controller.rb

Comments