- Learning Ruby on Rails
- Rails 2.1 Home
- Rails 2.1 Introduction
- Rails 2.1 Installation
- Rails 2.1 Framework
- Rails 2.1 Dir Structure
- Rails 2.1 Examples
- Rails 2.1 Database Setup
- Rails 2.1 Active Records
- Rails 2.1 Migrations
- Rails 2.1 Controllers
- Rails 2.1 Views
- Rails 2.1 Layouts
- Rails 2.1 Scaffolding
- Rails 2.1 and AJAX
- Rails 2.1 Uploads Files
- Rails 2.1 Sends Emails
- Advanced Ruby on Rails 2.1
- Rails 2.1 RMagick Guide
- Rails 2.1 Basic HTTP Auth
- Rails 2.1 Error Handling
- Rails 2.1 Routes System
- Rails 2.1 Unit Testing
- Advanced Ruby on Rails 2.1
- Rails 2.1 Tips & Tricks
- Quick Reference Guide
- Quick Reference Guide
- Ruby on Rails 2.1 Useful Resources
- Ruby on Rails 2.1 - Resources
- Ruby on Rails 2.1 - Discussion
Ruby on Rails 2.1 - The Models
Model Creation
Model.new # creates a new empty model Model.create( :field => 'value', :other_field => 42 ) # creates an object with the passed parameters and saves it Model.find_or_create_by_field( value ) # searches for a record where "field = value", creates # a new record if not found User.find_or_create_by_name_and_email( 'ramjoe', 'ram@example.com')
Model Relations
There are four ways of associating models - has_one, has_many, belongs_to, and has_and_belongs_to_many. Assuming the following four entities −
def Order < ActiveRecord::Base has_many :line_items belongs_to :customer end def LineItem < ActiveRecord::Base belongs_to :order end def Customer < ActiveRecord::Base has_many :orders has_one :address end def Address < ActiveRecord::Base belongs_to :customer end
Consider the following relationship −
def Category < ActiveRecord::Base has_and_belongs_to_many :products end def Product < ActiveRecord::Base has_and_belongs_to_many :categories end
Association Join Models
Consider the following relationship. It depicts how we can use joins while defining a relationship
class Author < ActiveRecord::Base has_many :authorships has_many :books, :through => :authorships end class Authorship < ActiveRecord::Base belongs_to :author belongs_to :book end class Book < ActiveRecord::Base has_one :authorship end @author = Author.find :first # selects all books that the author's authorships belong to. @author.authorships.collect { |a| a.book } selects all books by using the Authorship join model @author.books
rails-quick-guide.htm
Advertisements