创建一个不以ActiveRecord方式扩展的模型吗? e.g。
class Shipment
end
如果我这样做,我需要定义属性,或者我可以简单地执行:
shipment = Shipment.new
shipment.weight = 7
答案 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 :(得分:1)
是的,您可以通过在应用程序中创建一个类来创建非活动记录模型。
您仍然需要定义您希望它拥有的该类的属性,与其他任何属性一样。
Ryan Bates在这个主题上有一个简短的截屏视频: http://railscasts.com/episodes/121-non-active-record-model