没有桌子的 Rails 模型 [英] Rails Model without a table

查看:30
本文介绍了没有桌子的 Rails 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为颜色创建一个选择列表,但不想为颜色创建一个表格.我在任何地方都看到过,但在谷歌上找不到.

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?

或者是否有更好的 Rails 方法来做到这一点?

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.

推荐答案

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 将创建您的属性,您将使用 initialize() 和设置属性创建对象.

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

持久化的方法会告诉没有与数据库的链接.你可以找到这样的例子:http://railscasts.com/episodes/219-active-model?language=en&view=asciicast

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

这将向您解释逻辑.

这篇关于没有桌子的 Rails 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆