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

僤鯓⒐⒋嵵緔 提交于 2019-12-11 17:51:48

问题


This question is asked many times on 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_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.

  $(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. 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?


回答1:


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:

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



回答2:


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*/)


来源:https://stackoverflow.com/questions/53984862/how-to-store-string-as-array-in-database-column-using-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!