Sushil
Sushil

Reputation: 501

Serializing to array shows empty brackets and formats incorrectly in Rails

I have a department field in my org model where i want to store the list of department as an array. I have this in my model:

class Org < ActiveRecord::Base
   serialize :department, Array
   attr_accessible :name, :department
   before_validation :update_department
   validates :name, presence: true
   def update_department
    if department_changed? and department.is_a?(String)
     self.department = self.department.split(',').collect(&:strip) 
    end
  end
end

and the view:

<%= f.text_area :department, :cols => "10", :rows => "10" %>

now Whenever i try to sign up, the department field has [] present and when i try to update, the department is already ["[department1", "department2]"].

I want [] to be removed while signing up and department1, department2 to show up when updating. Also the array is saved incorrectly it should be ["department1", "department2"].

Please Help.

Upvotes: 0

Views: 202

Answers (1)

Kimooz
Kimooz

Reputation: 961

You Should join the array by comma

object.join(',')

in your example:

<%= f.text_area :department,value: @org.department.join(','), :cols => "10", :rows => "10" %>

Upvotes: 1

Related Questions