March 11, 2008

A Model Model

Filed under: model, rails — oomoo @ 1:38 pm

Example and details about a Rails Model:

*This beginning description was transcribed from a training video for which I am looking for the source to give credit. 

A “Model” is a Class that deals with the manipulation of data.  Classes allow the combination of data and methods in one place.  Because it is a full-blown Class, it can have any number of its own variables and methods.  The Model class is the perfect place for data validation for a Rails system.  It actually makes more sense to store data-based logic here than in the database (assuming that other systems are not monkeying with your data).  This is one of the reasons most Rails programmers don’t use database constraints (one of the big reasons is ActiveRecord doesn’t like it either). 

Generally, a Model Class is comprised of several things:

  • Associations  (Relationships to other tables in the database)
  • Validations  (special rails “validates…” statements)
  • Accessors  (creates “getter” and “setter” methods automatically)  (methods used to get/put data in a private class variable)
  • CallBacks  (hooks into the underlying rails logic that allow you to inject your code a specific steps)
  • Class Variables (@@varname, only one set maintained across all objects of the class)
  • Instance Variables (@varname, each object has its own set to manipulate at will)
  • Class Methods (generic logic methods not tied to specific data) (or operate on the class itself, like instance counters)
  • Instance Methods (any method that is not a class method)

# Associations ================================================

  has_one :order_account_type

  has_many :orders

  belongs_to :order_address

  belongs_to :order_user

  belongs_to :order 

# Validations =======================================================

  validates_presence_of :order_user_id, :order_address_id, :order_id

  validates_length_of :cc_number, :maximum => 20

  validates_format_of :cc_number, :with => /^[\d]*$/,

                      :message => ERROR_NUMBER

  validates_format_of :credit_ccv, :with => /^[\d]*$/,

                      :message => ERROR_NUMBER

  validates_numericality_of :expiration_month, :expiration_year 

# Accessors =======================================================

  attr_accessor :name, :promotion_code, cc_number 

# CALLBACKS =================================================================

  before_save :set_product_cost

  before_destroy{|record | Person.destroy_all “firm_id=#{record.id}”} 

  During the life cycle of an active record object, you can hook into 8 events:

      (-) save

      (-) valid?

      (1) before_validation

      (2) before_validation_on_create

      (-) validate

      (-) validate_on_create

      (3) after_validation

      (4) after_validation_on_create

      (5) before_save

      (6) before_create

      (-) create

      (7) after_create

      (8) after_save  

# CLASS VARIABLES =======================================================



# INSTANCE VARIABLES =======================================================



# CLASS METHODS =============================================================

  # List of years for dropdown in UI

  def self.years

    start_year = Date.today.year

    years = Array.new

            10.times do

      years << start_year

      start_year += 1


    return years


  # Search by order_number

  def self.search(search_term, count=false, limit_sql=nil)

    if (count == true) then

      sql = “SELECT COUNT(*) “


      sql = “SELECT DISTINCT orders.* “


      sql << “FROM orders “

      sql << “WHERE orders.order_number = ? “

      sql << “ORDER BY orders.created_on DESC “

      sql << “LIMIT #{limit_sql}” if limit_sql 

      arg_arr = [sql, search_term, “%#{search_term}%”] 

      if (count == true) then







# INSTANCE METHODS ==========================================================

  def status

    code = OrderStatusCode.find(:first, :conditions => [“id = ?”, self.order_status_code_id])



  def tax_cost

    (self.line_items_total) * (self.tax/100)


  def name

    return “#{billing_address.first_name} #{billing_address.last_name}”

Create A Model 

ruby script/generate model MyTable  (from Ruby command line… in your App’s folder) 






Edit The Model 

edit…  db/migrate/000_create_mytable.rb 

“RAKE” your changes 

rake db:migrate   (from Ruby command prompt,  in your App’s folder) 


ruby script/console   (from Ruby command prompt,  in your App’s folder)

     r = MyTable.new

     r.myfield = ‘new value’



Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: