0
我有一個form
,它傳遞一個數組到我的控制器的參數中,並持續導致ActiveModel::ForbiddenAttributesError
。我的create
函數調用另一個函數來修復這些數組參數並將這些部分合併爲一個字符串,但我認爲在這一點上太遲了。Rails 4:帶參數的參數
PARAMS
{ "remote"=>
{ "name"=>"",
"start_date"=>"9/27/2016",
"email"=>"",
"allergies"=>["Peanuts", "Soy Protein", "Dairy", ""],
}
}
控制器
def create
new_params = fix_params(params, ["allergies"])
remote_params = new_params["remote"]
@remote = Remote.new(remote_params)
respond_to do |format|
if @remote.save
format.html { redirect_to root_path, notice: 'Remote was successfully created.' }
format.json { render :show, status: :created, location: @remote }
else
format.html { render :new }
format.json { render json: @remote.errors, status: :unprocessable_entity }
end
end
end
def fix_params(params, fields)
fields.each do |field|
to_change = params[:remote][field]
new_param = to_change.join(", ").strip()
params[:remote][field] = new_param || ""
end
return params
end
也許有更好的方式來傳遞這些變量?
'ActiveModel'錯誤建議在模型中有物體擋住這一點。你可以張貼嗎?另外,爲什麼你需要'fix_params'方法,你想達到什麼目的?毫無疑問,這是一種更有力的方式。 – Matt
你是對的,這是由於模型,我希望我有一種不同的方式來完成我在'fix_params'中做的事情。該函數基本上需要一個參數數組,並將它們組合成一個字符串 –
有一個更好的方法來做到這一點,在你的模型中,定義一個自定義setter def過敏=(價值)自我[:過敏] = value.is_a?(陣列)? value.join(',').strip:值結束。任何時候設置模型都會修復該值。 – arieljuod