[英]Rails - ActionController::Parameters include controller value with form values
我有一個會話變量(user_id),我想將其作為外鍵包含在用戶要插入的記錄中。 使用默認的params定義,我將所有表單值都通過表單提交到控制器的entity.update(params)方法。 該代碼看起來像
def brand_params
@brand_params = params.require(:brand).permit(:name, :brand_type, :profile_id)
end
更新方法看起來像
if @brand.update(brand_params)
format.html { redirect_to @brand, notice: 'Widget was successfully updated.' }
format.json { render :show, status: :ok, location: @brand }
else
format.html { render :edit }
format.json { render json: @brand.errors, status: :unprocessable_entity }
end
現在,我想將:profile_id會話變量附加到@brand_params並在這里跟隨其他線程,我嘗試了一個setter方法:
def set_brand_params(key, val)
if @brand_params != nil
@brand_params[key] = val
end
end
但是,將其命名為@brand_params始終為零。 嘗試直接添加到brand_params哈希中不起作用,因為這是一種更好的方法。 如果有更好的方法來滿足這個用例(我假設是常見的),我會很高興! 否則,我想知道為什么var總是為零,盡管在這種情況下,至少brand_params方法將其視為已定義且具有值。 我在向服務器端的ActionController :: Parameters添加值中獲得了此解決方案
這是請求的更新方法:
def update
puts "update"
set_brand_params("profile_id", session[:prof])
respond_to do |format|
if @brand.update(brand_params)
format.html { redirect_to @brand, notice: 'Widget was successfully updated.' }
format.json { render :show, status: :ok, location: @brand }
else
format.html { render :edit }
format.json { render json: @brand.errors, status: :unprocessable_entity }
end
end
end
我不同意將您的數據與參數合並。 因為您必須僅允許字段,所以您希望用戶進行更新。 在這種情況下,您不希望用戶更新品牌的profile_id
,這是安全性最佳做法。
然后brand_params必須為:
def brand_params
@brand_params = params.require(:brand).permit(:name, :brand_type)
end
您的方法更新可能如下所示:
def update
@brand = Brand.find(params[:id])
@brand.assign_attributes(profile_id: session[:prof])
respond_to do |format|
if @barnd.update(brand_params)
format.html { redirect_to @brand, notice: 'Widget was successfully updated.'}
format.json { render :show, status: :ok, location: @brand }
else
format.html { render :edit }
format.json { render json: @brand.errors, status: :unprocessable_entity }
end
end
end
您根本不需要方法set_brand_params
。
如果這樣做不能解決問題,請發布入口控制器,希望我們能找到問題。
編輯:添加response_to。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.