0

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?

3
  • You can split string & use it as array by using str.split(/\s*,\s*/) which will remove leading & ailing whitespaces also Commented Dec 31, 2018 at 9:39
  • @ray at what stage I need to do this please? Commented Dec 31, 2018 at 10:06
  • check answer posted, whether it work Commented Dec 31, 2018 at 10:19

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Should I take the keywords without adding custom commas in the end of each keyword now?
It’s up to you and the desired implementation of both dump and load; I just showed the generic receipt.
This is real good one, but I am getting nil for what inside load method, why?
@ray I have no idea.
@ray Same here.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.