Run
Run

Reputation: 896

Can I have a way to customize field settings in rails activerecord?

I want to add a array field(named tags) in my sqlite database, so I have done some followings:

# migration
add_column :tags, :string

# controller
def update
  tags = params[:tags] # a array from frontend
  project.tags = tags.join(',')
  project.save!
end

def show
  project_hash = project.as_json
  project_hash['tags'] = project_hash['tags'].split(',')
  render json: project_hash
end

But I want to customize field setting and getting method directyly in active model, which is like below:

# model
def tags=(array)
  self.real_tags_column = array.join(',')
end

def tag
  self.real_tags_column.split(',')
end

Upvotes: 1

Views: 50

Answers (2)

Darpan Chhatravala
Darpan Chhatravala

Reputation: 520

Yes you can use Active record serialize attribute instead of customisation.

# Serialize a preferences attribute.
class User < ActiveRecord::Base
  serialize :preferences
end

# Serialize preferences using JSON as coder.
class User < ActiveRecord::Base
  serialize :preferences, JSON
end

# Serialize preferences as Hash using YAML coder.
class User < ActiveRecord::Base
  serialize :preferences, Hash
end

Please review ActiveRecord::AttributeMethods::Serialization::ClassMethods & how to save array to database in rails

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230461

It should work like this:

def tags
  self['tags'].split(',')
end

def tags=(array)
  self['tags'] = array.join(',')
end

If it doesn't, try read_attribute/write_attribute.

Upvotes: 2

Related Questions