[英]How can I get data from multiple form fields, and then submit them with the same form into a single database cell as a array?
這是我在Rails表單中的一部分:
# 2 fields that should have values passed into an array
<%= f.label "test1" %>
<%= text_field_tag(:test1) %>
<%= f.label "test2" %>
<%= text_field_tag(:test2) %>
# hidden field to (hopefully) receive the array data (same form)
<%= f.hidden_field :subtypes, :value => @subtypes %>
這是在我的控制器中:
def update
if @anomaly.update(anomaly_params)
redirect_to anomaly_path(@anomaly)
flash[:success] = "You have successfully updated the anomaly"
else
render :edit
flash[:error] = @anomaly.errors.full_messages
end
end
該方法將在各種方法之前運行 :(文件頂部的before_action)
# before_action :subtypes_array, only: [:new, :edit, :create, :update]
def subtypes_array
@subtypes = []
field1 = params[:test1]
field2 = params[:test2]
@subtypes << field1
@subtypes << field2
end
我在控制器中也有這個:
# before_action :set_anomaly, only: [:show, :edit, :update, :destroy]
def set_anomaly
@anomaly = Anomaly.find(params[:id])
end
我有Rails 4強大的參數,以允許來自各個領域的數據通過。 該表單可以正常工作,但是來自兩個字段的數據永遠不會進入數據庫。
我已經有一個數據庫列,可以接收帶有字符串值的數組:
class AddSubtypesToAnomalies < ActiveRecord::Migration
def change
add_column :anomalies, :subtypes, :string, array: true, default: []
end
end
從控制台,我可以毫無問題地傳遞數組。
我想知道如何使這項工作?
更新:
private
def anomaly_params
params.require(:anomaly).permit(:test1, :test2, :name, :description, :subtypes)
end
您的text_field_tag必須嵌套在對象下
<%= text_field_tag("anomaly[test1]") %>
<%= text_field_tag("anomaly[test2]") %>
這是因為您正在使用的form_for設置了anomaly下的所有其他字段。 anomaly_params僅在您的更新方法中捕獲 異常情況下的內容。
由於您在數據庫字段中使用了一個數組,並且選擇為該數組使用多個字段,因此需要同時在create和update controller方法中捕獲它。 使用我在這里編寫的相同text_field_tags,您可以執行以下操作:
def create
create_subtypes
if @anmaly.save(anomaly_params)
...
def update
create_subtypes
if @anomaly.update(anomaly_params)
...
private
def create_subtypes
params['anomaly']['subtypes'] = Array(params['anomaly']['subtypes']) << params['anomaly'].delete('test1')
params['anomaly']['subtypes'] = Array(params['anomaly']['subtypes']) << params['anomaly'].delete('test2')
end
要在數組開頭處處理空項目,請執行以下操作:
def create_subtypes
params['anomaly']['subtypes'] = Array(params['anomaly']['subtypes'].presence).compact << params['anomaly'].delete('test1')
params['anomaly']['subtypes'] = Array(params['anomaly']['subtypes'].presence).compact << params['anomaly'].delete('test2')
end
僅創建一個常規:subtypes表單字段並讓用戶手動輸入自己的逗號分隔列表而不是使用test1和test2可能會更容易。
您必須告訴控制器subtypes
參數是一個數組,否則就不會這樣處理,並且由於您具有強大的參數,這是這樣做的方法:
private
def anomaly_params
params.require(:anomaly).permit(:test1, :test2, :name, :description, :subtypes=> [])
end
同時使用完整的哈希標簽作為參數
field1 = params[:anomaly][:test1]
field2 = params[:anomaly][:test2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.