如何在 Rails 中处理不属于模型且本身不属于模型的列表数据?
在我的 Rails 项目中,我有不同的数据列表,我必须通过 CRUD 操作来维护这些数据,并且每个列表不值得一个模型或整个脚手架来维护它,在 Rails 上处理此问题的最佳方法是什么?
现在,我使用名称为:字符串内容:文本的列表模型将每个列表保存为列表记录,并在我的应用程序中需要某些列表时进行一些解析。这是我的实际列表模型:
class NoListException < Exception
end
class List < ActiveRecord::Base
validates :name, uniqueness: true
def self.container_types
get_list('container_types').collect do |b|
b.split(',').collect {|c| c.split(':').last }
end.collect {|p| "#{p.last} - #{p.first}" }
end
def self.location_categories
get_id_value_list('location_categories')
end
def self.services_types
get_list('services_types')
end
private
def self.get_id_value_list(name)
get_list(name).collect do |b|
(b.split(',').collect {|c| c.split(':').last }).rotate
end
end
def self.get_list(name)
list = List.find_by_name(name)
raise NoListException if list.nil?
list.content.split(';')
end
end
我认为这是一个非常常见的问题,因此我问是否有更好的方法来处理这些列表?
In my rails project I have diferent list of data that I have to mantain with CRUD operations and each list doesn't deserve a model or an entire scaffolding to maitain it, what's the best way to handle this on rails?
Now I'm using a List model with name:string content:text to save each list as a list record and do some parsing when I need some list in my app. Here is my actual list model:
class NoListException < Exception
end
class List < ActiveRecord::Base
validates :name, uniqueness: true
def self.container_types
get_list('container_types').collect do |b|
b.split(',').collect {|c| c.split(':').last }
end.collect {|p| "#{p.last} - #{p.first}" }
end
def self.location_categories
get_id_value_list('location_categories')
end
def self.services_types
get_list('services_types')
end
private
def self.get_id_value_list(name)
get_list(name).collect do |b|
(b.split(',').collect {|c| c.split(':').last }).rotate
end
end
def self.get_list(name)
list = List.find_by_name(name)
raise NoListException if list.nil?
list.content.split(';')
end
end
I think is a very common problem, because of that I ask if there are a better way to handle those lists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个模型没有脚手架支撑也不错。我经常使用类别或标签之类的模型来执行此操作,这些模型通常由它们所作用的模型创建和管理。因此,不要为一个简单的模型构建整个脚手架而感到有压力。
如果您不需要将数据持久保存到数据库,那么您始终可以使用 ActiveModel,或者如果您确实需要持久保存并且可以找到另一个模型来搭载,请研究序列化,这是存储松散数据的好方法
Its not bad to have a model with no scaffolding to support it. I often do this with category or tag like models which are often created and managed by the models they act upon. So don't feel pressured to build out a whole scaffolding for a simple model.
If you don't need to persist the data to the database then you can always use ActiveModel, or if you do need to persist and can find another model to piggy back ontop of, look into serialization, its a good way to store loose data