0

I am not able to store array in database column.

text_field:

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

controller params:

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

model:

serialize :keywords, Array

migration:

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

So, if someone writes, abc mbc csx and hit submit it should save in db column as array like below:

["abc", "mbc", "csx"]

now I want to store it as array in column but its not storing properly. it stores as:

["abc mbc csx"]

Also what are the best practices to deal with these cases?

16
  • In your model, serialize :keywords, Array, did you try just serialize :keywords without the Array? Commented Dec 31, 2018 at 16:01
  • What do your submitted parameters look like? Commented Dec 31, 2018 at 16:04
  • @AadityaMaheshwari still returns ["voip man cat"] Commented Dec 31, 2018 at 16:06
  • @jvillian they look like: ["voip man cat"] or "keywords"=>["voip man cat"] Commented Dec 31, 2018 at 16:06
  • @LearningROR I assume you already tried restarting the server & rails console after editing the model? Commented Dec 31, 2018 at 16:09

2 Answers 2

0

Solution for this use case:

Removed serialize array from model. Post without array params.

Post with commas on the front end. On the view, use .join(',')

Sign up to request clarification or add additional context in comments.

Comments

0

You can keep storing it as a text with a separator like a "," for example. And you convert it to an array when you read it as the following:

keywords = Product.find(id).keywords.split(",")

Comments

Your Answer

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