Rails Model without a table

2019-01-13 20:47发布

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 question is: How can I put the colors in a model without a database table?

Or is there a better rails way for doing that?

I have seen someone putting an array or a hash directly in the model, but now I couldn't find it.

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-13 20:59

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
查看更多
\"骚年 ilove
3楼-- · 2019-01-13 21:05
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.

查看更多
看我几分像从前
4楼-- · 2019-01-13 21:07

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

查看更多
做个烂人
5楼-- · 2019-01-13 21:11

The answers are fine for 2013 but now rails 4 has extracted all the database independent features out of ActiveRecord 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
查看更多
登录 后发表回答