[英]How to Store the text fields array data in database without using loop using rails
I am new in ror and I am trying from 4 hours to store the data of form of textfields array like this 我是ror的新手,我试图从4个小时开始存储像这样的textfields数组形式的数据
<input type="text" name="custom_field[names][]" class="form-control full-width" placeholder = "Name">
<input type="text" name="custom_field[length_limit][]" class="form-control full-width" placeholder = "Length Limit">
I want to store the arrays coming into the form in database columns of name and length limit. 我想将进入表单的数组存储在名称和长度限制的数据库列中。 I don't want to use loop to do this job.
我不想使用循环来完成这项工作。
I am doing this in controller 我正在控制器中执行此操作
user = CustomField.create(:name=> params[:names])
But it is giving ERROR: null value in column "name" violates not-null constraint DETAI
但是它给出了
ERROR: null value in column "name" violates not-null constraint DETAI
params are 参数是
{"names"=>["tester", "another tester"], "length_limit"=>["aaaaaa222", "aaaaaa222"]
I am using postgresql 我正在使用postgresql
How can I do this? 我怎样才能做到这一点?
params[:names]
is an array, so it doesn't make sense to save it to a string/text field in postgres, which is what CustomField.create(:name=> params[:names])
does. params[:names]
是一个数组,因此将其保存到postgres中的字符串/文本字段中是没有意义的, CustomField.create(:name=> params[:names])
这样做的。
Essentially, it expands to CustomField.create(:name=> ["tester", "another tester"])
. 从本质上讲,它扩展为
CustomField.create(:name=> ["tester", "another tester"])
。 If you want to create a separate CustomField record for each name, then you could do something like: 如果要为每个名称创建单独的CustomField记录,则可以执行以下操作:
params[:names].each do |name|
CustomField.create(:name => name)
end
To create the CustomField records with the corresponding length_limit
, you could do something like: 要使用相应的
length_limit
创建CustomField记录,可以执行以下操作:
params[:names].zip(params[:length_limit]).each do |name, limit|
CustomField.create(:name => name, :length_limit => limit)
end
Note that this doesn't account for errors where the name
s and length_limit
s don't match. 请注意,这不能解决
name
s和length_limit
不匹配的错误。 You might want to add some validation to make sure that all the required data is present. 您可能需要添加一些验证,以确保所有必需的数据都存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.