0

So I'm trying to convert a string that I get from a hidden_field to an array before I save it to the database and I'm having no luck. My Active record datatype is:

add_column :contractors, :regions, :text, array: true

My model looks like this

class Contractor < ActiveRecord::Base
  before_validation :make_array

private
    def make_array
        self.regions = self.regions.split(',')
    end
end

and I'm getting the value from a hidden field

<%= f.hidden_field :regions, value: "1,2,3" %>

It seems if I have array: true on database column self.regions is an empty array when the callback runs. If I remove array:true the string is converted to an array with the callback but it won't save to the database (can't cast Array to text). I've tried adding serialize: :regions but I get this error:

ERROR:  array value must start with "{" or dimension information.

I've also tried sending an array from the hidden field with no luck.

Any ideas what I am doing wrong?

2 Answers 2

1

Rails (or ActiveRecord) is trying to cast the value assigned to regions (from a controller perhaps) to an array, which results in an empty array given the input. A quick-n-dirty solution is to do the split before assigning the value, like from a controller. Another one is to use an attr_accessor to store the region ids, then use its value in your model callback, like this

# the model
class Contractor < ActiveRecord::Base
   attr_accessor :region_ids # Rails 4? whitelist it in the controller. Rails 3? Whitelist it here using attr_accessible
   # ... the rest
   def make_array
     self.regions = region_ids.split(',')
   end
end

// the view
<%= f.hidden_field :region_ids, value: "1,2,3" %>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion. Sounds like having my regions be objects is smarter way to go, and I may eventually do that. I just wanted to see if I could just turn a string from an input field into an array.
0

I would suggest using serialize option in this case so that you can easily convert a string into array without worrying too much about other things. You can read more here: http://thelazylog.com/posts/using-serialize-option-in-ruby-on-rails

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.