开发者

How to hanlde list data that doesn't belong to a model an isn't a model by its own in rails?

开发者 https://www.devze.com 2023-03-08 00:54 出处:网络
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 hand

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(',').coll开发者_Python百科ect {|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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号