我想在我的sqlite数据库中添加一个数组字段(命名标签),所以我做了以下工作:
# 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
但是我想直接在活动模型中自定义字段设置和获取方法,如下所示:
# model
def tags=(array)
self.real_tags_column = array.join(',')
end
def tag
self.real_tags_column.split(',')
end
答案 0 :(得分:2)
它应该像这样工作:
def tags
self['tags'].split(',')
end
def tags=(array)
self['tags'] = array.join(',')
end
如果没有,请尝试read_attribute
/ write_attribute
。
答案 1 :(得分:0)
是的,您可以使用活动记录序列化属性来代替自定义。
# 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
请查看ActiveRecord::AttributeMethods::Serialization::ClassMethods和how to save array to database in rails