Rails Model without a table

后端 未结 5 961
你的背包
你的背包 2020-12-05 02:24

I want to create a select list for lets say colors, but dont want to create a table for the colors. I have seen it anywhere, but can\'t find it on google.

My questi

相关标签:
5条回答
  • 2020-12-05 02:41

    The answers are fine for 2013 but since Rails 4 all the database independent features of ActiveRecord are extracted into ActiveModel. Also, there's an awesome official guide for it.

    You can include as many of the modules as you want, or as little.

    As an example, you just need to include ActiveModel::Model and you can forgo such an initialize method:

    def initialize(attributes = {})
      attributes.each do |name, value|
        send("#{name}=", value)
      end
    end
    

    Just use:

    attr_accessor :name, :age
    
    0 讨论(0)
  • 2020-12-05 02:44

    The easiest answer is simply to not subclass from ActiveRecord::Base. Then you can just write your object code.

    0 讨论(0)
  • 2020-12-05 02:50

    If you want to have a select list (which does not evolve) you can define a method in your ApplicationHelper that returns a list, for example:

     def my_color_list
       [
         "red",
         "green",
         "blue"
       ]
     end
    
    0 讨论(0)
  • If the reason you need a model without an associated table is to create an abstract class real models inherit from - ActiveRecord supports that:

    class ModelBase < ActiveRecord::Base
      self.abstract_class = true
    end
    
    0 讨论(0)
  • 2020-12-05 03:07
    class Model
    
      include ActiveModel::Validations
      include ActiveModel::Conversion
      extend ActiveModel::Naming
    
      attr_accessor :whatever
    
      validates :whatever, :presence => true
    
      def initialize(attributes = {})
        attributes.each do |name, value|
          send("#{name}=", value)
        end
      end
    
      def persisted?
        false
      end
    
    end
    

    attr_accessor will create your attributes and you will create the object with initialize() and set attributes.

    The method persisted will tell there is no link with the database. You can find examples like this one: http://railscasts.com/episodes/219-active-model?language=en&view=asciicast

    Which will explain you the logic.

    0 讨论(0)
提交回复
热议问题