简体   繁体   English

如何使用Ruby on Rails将字符串存储为数据库列中的数组

[英]How to store string as array in database column using Ruby on Rails

This question is asked many times on SO. 在SO上多次问过这个问题。 The main problem is nothing got fits into my situation. 主要问题是没有什么适合我的情况。

Case is, I am not able to store typed content as array in database column. 情况是,我无法将键入的内容作为数组存储在数据库列中。

text_field whose code is: text_field,其代码为:

= text_field_tag 'product[keywords][]', @product.keywords, class: 'tab-input
product_keywords'

In controller strong parameters are: 在控制器中,强参数是:

params.require(:product).permit(:id, :name, :keywords => [])

Jquery code that is not not removing value upon deletion when typed wrong value but it add commas after each element as I want to take commas seperated value in one column. jQuery代码在键入错误值时不会在删除时删除值,但是它在每个元素后添加逗号,因为我想在一行中使用逗号分隔的值。

  $(document).on 'keyup', '.product_keywords', ->
    keyword = @value.replace(/(\w)[\s,]+(\w?)/g, '$1, $2')
    if keyword != @value
      @value = keyword
    return

model code: 型号代码:

serialize :keywords, Array

migration code: 迁移代码:

class AddKeywordsToProducts < ActiveRecord::Migration[5.1]
  def change
    add_column :products, :keywords, :text
  end
end

So, if someone writes, abc and hit space a comma is added in the end. 因此,如果有人写作,abc并按空格,最后会添加一个逗号。 after three typed words it will look like: 在三个键入的单词之后,它将看起来像:

abc, dbx, she

now I want to store it as array in column but its not storing properly. 现在我想将其存储为列中的数组,但存储不正确。 it stores as: 它存储为:

["abc, dbx, she"]

Also please can anybody tell me the best cases to handle these cases? 还请有人告诉我处理这些案件的最佳情况吗? Plus best practices to deal with such cases using ruby so I will learn it for future? 再加上使用红宝石处理此类案件的最佳实践,以便将来我能学到?

You probably want a custom serializer as shown here . 你可能想自定义序列如图所示这里 So instead of: 所以代替:

serialize :keywords, Array

You might do somewhat like: 您可能会这样做:

serialize :keywords, KeywordSerializer

And somewhere in helpers : helpers某个地方:

class KeywordSerializer 
  def self.dump(what)
    what.join(", ")
  end
  def self.load(what)
    what.split(/\s*,\s*/)
  end
end

Passing array elements using single form tag is not possible to pass as a array and passing array as a string, you need to process it near white-listing your params, 使用单一表单标签传递数组元素不能作为数组传递,而不能将数组作为字符串传递,您需要在将参数列入白名单的附近对其进行处理,

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM