我已經使用Rails腳手架進行了一些測試,並且試圖爲已經存在的模型生成控制器和視圖。在form_for中找不到參數
我試圖編輯我的模型的值。
在控制器中的所有需要的方法有哪些,甚至還有:
# Never trust parameters from the scary internet, only allow the white list through.
def tag_params
params[:tag]
end
我想從我的模型(名爲標籤)更新的唯一價值是:名字,所以我編輯了tag_params
方法是這樣的:
# Never trust parameters from the scary internet, only allow the white list through.
def tag_params
params[:tag].require(:tag).permit(:name)
end
因爲我通常做,但現在我得到一個param not found: tag
例外。
但是,如果我把它寫這樣
# Never trust parameters from the scary internet, only allow the white list through.
def tag_params
params[:tag].permit(:name)
end
它工作正常的。這是爲什麼?
視圖中的的form_for聲明如下所示:
<%= form_for(@tag) do |f| %>
對於那些誰也不知道腳手架方法怎麼看起來像控制器,這裏是它的一部分:
# GET /tags/1/edit
def edit
end
# PATCH/PUT /tags/1
# PATCH/PUT /tags/1.json
def update
respond_to do |format|
if @tag.update(tag_params)
format.html { redirect_to tags_path, notice: 'Tag was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @tag.errors, status: :unprocessable_entity }
end
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def tag_params
params[:tag]
end
'params [:tag]'與'params.require(:tag)'相同嗎? – Pacane
不,「params [:tag]'是包含標籤屬性(即名稱)的實際散列。 'params.require(:tag)'是一種在參數散列中需要標籤參數的方法。 – aromero
好的,謝謝你的解釋:) – Pacane