[英]how to split the array and store into the database in ruby on rails?
[英]How to store string as array in database column using Ruby on Rails
在SO上多次问过这个问题。 主要问题是没有什么适合我的情况。
情况是,我无法将键入的内容作为数组存储在数据库列中。
text_field,其代码为:
= text_field_tag 'product[keywords][]', @product.keywords, class: 'tab-input
product_keywords'
在控制器中,强参数是:
params.require(:product).permit(:id, :name, :keywords => [])
jQuery代码在键入错误值时不会在删除时删除值,但是它在每个元素后添加逗号,因为我想在一行中使用逗号分隔的值。
$(document).on 'keyup', '.product_keywords', ->
keyword = @value.replace(/(\w)[\s,]+(\w?)/g, '$1, $2')
if keyword != @value
@value = keyword
return
型号代码:
serialize :keywords, Array
迁移代码:
class AddKeywordsToProducts < ActiveRecord::Migration[5.1]
def change
add_column :products, :keywords, :text
end
end
因此,如果有人写作,abc并按空格,最后会添加一个逗号。 在三个键入的单词之后,它将看起来像:
abc, dbx, she
现在我想将其存储为列中的数组,但存储不正确。 它存储为:
["abc, dbx, she"]
还请有人告诉我处理这些案件的最佳情况吗? 再加上使用红宝石处理此类案件的最佳实践,以便将来我能学到?
你可能想自定义序列如图所示这里 。 所以代替:
serialize :keywords, Array
您可能会这样做:
serialize :keywords, KeywordSerializer
在helpers
某个地方:
class KeywordSerializer
def self.dump(what)
what.join(", ")
end
def self.load(what)
what.split(/\s*,\s*/)
end
end
使用单一表单标签传递数组元素不能作为数组传递,而不能将数组作为字符串传递,您需要在将参数列入白名单的附近对其进行处理,
permitted_params = params.require(:product).permit(:id, :name, :keywords => [])
permitted_params[:keywords] = permitted_params[:keywords][0].split(/\s*,\s*/)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.