[英]Forwarding post parameters in a redirect_to rails
在我的Rails應用程序中,我希望用戶能夠以“新”形式選擇一個選項,但是如果該選項已經存在,則希望它更新當前選項。
到目前為止,我的create方法中有以下內容:
def create
@cost = Cost.new(cost_params)
if Cost.exists?(:category => @cost.category, :option => @cost.option)
redirect_to action: 'update', id: Cost.where(:category => @cost.category, :option => @cost.option).first.id
else
respond_to do |format|
if @cost.save
format.html { redirect_to action: 'index', status: 303, notice: [true, 'Cost was successfully created.'] }
format.json { render json: @cost, status: :created, location: @cost }
else
format.html { render action: "new" }
format.json { render json: @cost.errors, status: :unprocessable_entity }
end
end
end
end
問題是它將我重定向到例如cost/9
url,它呈現了顯示頁面。 我希望id與cost_params一起直接發送到update方法:
def update
@cost = Cost.find(params[:id])
respond_to do |format|
if @cost.update_attributes(cost_params)
format.html { redirect_to action: 'index', status: 303, notice: [true, 'Cost was successfully updated.'] }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @cost.errors, status: :unprocessable_entity }
end
end
end
應該重定向到索引頁面。
有什么有效的方法可以做到這一點嗎?
HTTP重定向總是導致GET請求,而不是POST請求,因此重定向到update
並沒有多大意義。 這不是Rails的問題,而是HTTP的工作方式。
如果要自動更新相關記錄,則必須在create
動作中執行此操作。 一種簡單但懶惰的方法是從update復制代碼並將其粘貼到create
if
分支中。 更正確的方法是將update
的相關部分提取到單獨的私有方法中,並從create
和update
調用該方法,例如:
def create
@cost = Cost.new(cost_params)
if Cost.exists?(:category => @cost.category, :option => @cost.option)
@cost = Cost.where(:category => @cost.category, :option => @cost.option).first
really_update
else
respond_to do |format|
if @cost.save
format.html { redirect_to action: 'index', status: 303, notice: [true, 'Cost was successfully created.'] }
format.json { render json: @cost, status: :created, location: @cost }
else
format.html { render action: "new" }
format.json { render json: @cost.errors, status: :unprocessable_entity }
end
end
end
end
def update
@cost = Cost.find(params[:id])
really_update
end
private def really_update
respond_to do |format|
if @cost.update_attributes(cost_params)
format.html { redirect_to action: 'index', status: 303, notice: [true, 'Cost was successfully updated.'] }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @cost.errors, status: :unprocessable_entity }
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.