While following rails routes to build the whole CRUD system, I encountered an issue where an 302 status code would occur after performing create, update and delete actions. The page would be redirected to "show" instead of "index" as I coded.
controller.rb
class CandidatesController < ApplicationController
def index
@candidates = Candidate.all
end
def new
@candidate = Candidate.new
end
def create
@candidate = Candidate.new(filtered)
if @candidate.save
flash[:notice] = "Successfully Added!"
redirect_to 'candidates_path'
else
render :new
end
end
def show
@candidate = Candidate.find_by(id: params[:id])
end
def edit
@candidate = Candidate.find_by(id: params[:id])
end
def update
p @candidate = Candidate.find_by(id: params[:id])
if @candidate.update(filtered)
flash[:notice] = "Candidate Updated :)"
redirect_to 'candidates_path'
else
render :edit
end
end
def destroy
p @candidate = Candidate.find_by(id: params[:id])
@candidate.destroy
flash[:notice] = "Successfully Deleted!"
redirect_to 'candidates_path'
end
private
def filtered
params.require(:candidate).permit(:name, :party, :age, :politics)
end
end
Views:index
<h1> Candidate Index </h1>
<div><%= link_to 'Add new candidate', new_candidate_path %></div>
<div><%= flash[:notice] %> </div>
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>Party</td>
<td>Politics</td>
</tr>
<% @candidates.each do |candidate| %>
<tr>
<td><%= link_to candidate.name, candidate_path(candidate.id) %></td>
<td><%= candidate.age %></td>
<td><%= candidate.party %></td>
<td><%= candidate.politics %></td>
<td><%= link_to 'edit', edit_candidate_path(candidate.id) %></td>
<td><%= link_to 'delete', candidate_path(candidate.id), method: 'delete', data: {confirm: "Please confirm delete"} %></td>
</tr>
<% end %>
</table>
Views: show
<h1> Candidate Info </h1>
<% if @candidate %>
<tr>
<td><%= @candidate.name %></td>
<td><%= @candidate.age %></td>
<td><%= @candidate.party %></td>
<td><%= @candidate.politics %></td>
</tr>
<% else %>
<h2>No record found </h2>
<% end %>
<div>
<%= link_to 'HOME', candidates_path %>
</div>
from browser
And after refreshing the page, it always go to "show" instead of "index".
Routes created
Does anyone know why?
CodePudding user response:
Use the candidates_path
method, not the 'candidates_path'
string:
redirect_to candidates_path