Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save array in Active Admin Rails 4?

I am using Active Admin in Rails 4. In my model i have one field which is an Postgres array type when i am creating the object it is passing in background but it is not saving to the database. So what i need to do to save the array field in database through Active Admin.

Thanks

like image 494
Mohd Anas Avatar asked Oct 22 '13 13:10

Mohd Anas


1 Answers

You have hack stuff since active admin doesn't support it out of the box, it seems.

Though this answer is old, it works: How do you handle serialized edit fields in an Active Admin resource?

Here is a summary of how I handled this situation. I added an accessor to the model which can turn the Array into a string joined by a linefeed and split it back to an Array.

# app/models/domain.rb
class Domain < ActiveRecord::Base
  serialize       :names, Array
  attr_accessor   :names_raw

  def names_raw
    self.names.join("\n") unless self.names.nil?
  end

  def names_raw=(values)
    self.names = []
    self.names=values.split("\n")
  end
end

then, in my admin resource for domain, instead of using the :names field, I used the :names_raw field. setting this value would save the names Array with the new values.

# app/admin/domains.rb
form do |f|
  f.inputs "Domain" do
    f.input :names_raw, :as => :text
  end
  f.actions
end
like image 163
Vedant Agarwala Avatar answered Sep 28 '22 07:09

Vedant Agarwala