-1

Is creating a model that does not extend ActiveRecord the way to do this? e.g.

class Shipment
end

And if I do this do I need to define properties, or can I simply do:

shipment = Shipment.new
shipment.weight = 7
drewwyatt
  • 5,989
  • 15
  • 60
  • 106

2 Answers2

3

Generally in OOP you can define a class and inheritance is an option.

In Rails (ruby) you can define a class without extending ActiveRecord

So this:

class Shipment
end

is a valid ruby class, and you can initiate an object from it using shipment = Shipment.new as you guessed

However if you try:

shipment.weight = 7

You will get Undefined method 'weight' for shipment which does make sense , right? because you never defined some way to set a weight attribute for the Shipment class!

You should define a weight setter or getter or both and ruby makes it super easy to do so:

class Shipment
  attr_accessor :weight
end

Which is equivalent to:

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

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

Reading links:

  1. Ruby docs (http://www.ruby-doc.org/core-2.1.1/Class.html)
  2. This SO question explains how setter and getter works in ruby
  3. Both answers to this SO question are useful (understanding ruby classes, attributes)
Community
  • 1
  • 1
Nimir
  • 5,727
  • 1
  • 26
  • 34
1

Yes, you can create non active record model by creating a class within your application.

You will still need to define the properties of that class that you would like it have, as with any other.

Ryan Bates has a short screencast about the topic at: http://railscasts.com/episodes/121-non-active-record-model

maxshelley
  • 166
  • 2
  • 5