在按照 rails 路線構建整個 CRUD 系統時,我遇到了一個問題,即在執行創建、更新和洗掉操作后會出現 302 狀態代碼。該頁面將被重定向到“顯示”而不是我編碼的“索引”。
控制器檔案
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
瀏覽次數:索引
<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>
觀看次數:顯示
<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>
** 資訊**

從瀏覽器

重繪 頁面后,它總是轉到“顯示”而不是“索引”。
創建的路線

有誰知道為什么?
uj5u.com熱心網友回復:
使用candidates_path方法,而不是'candidates_path'字串:
redirect_to candidates_path
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369454.html
標籤:红宝石轨道 重定向 http-status-code-302
