如何创建不需要存储在数据库中的类/对象?

时间:2014-05-10 19:02:32

标签: ruby-on-rails

创建一个不以ActiveRecord方式扩展的模型吗? e.g。

class Shipment
end

如果我这样做,我需要定义属性,或者我可以简单地执行:

shipment = Shipment.new
shipment.weight = 7

2 个答案:

答案 0 :(得分:3)

通常在 OOP 中,您可以定义一个类,继承是一个选项。

在Rails(ruby)中,您可以定义一个类而不扩展ActiveRecord

所以这个:

class Shipment
end

是一个有效 ruby​​类,您可以在猜测时使用shipment = Shipment.new从中启动一个对象

但是如果你尝试:

shipment.weight = 7

你会得到Undefined method 'weight' for shipment哪个有意义,对吧?因为你从未定义某种方法来为weight类设置Shipment属性!

你应该定义一个weight setter或getter或两者并且ruby让它变得非常容易:

class Shipment
  attr_accessor :weight
end

相当于:

class Shipment
  #getter
  def weight
    #return the weight
    @weight
  end

  #setter
  def weight=(weight)
    #set the weight
    @weight = weight
  end
end

阅读链接:

  1. Ruby docs(http://www.ruby-doc.org/core-2.1.1/Class.html
  2. SO question解释了setter和getter在ruby中的工作原理
  3. 这个SO question的答案都很有用(理解ruby类,属性)

答案 1 :(得分:1)

是的,您可以通过在应用程序中创建一个类来创建非活动记录模型。

您仍然需要定义您希望它拥有的该类的属性,与其他任何属性一样。

Ryan Bates在这个主题上有一个简短的截屏视频: http://railscasts.com/episodes/121-non-active-record-model